Resolves problems with variables, references, copies, and scopes in Python _python

Source: Internet
Author: User
Tags garbage collection shallow copy in python

In Python, variables are not the same type, which is not the same as most of the editing languages you've seen before. When you use a variable, you don't need to declare it in advance, just assign a value to that variable. However, when you use a variable, you must assign a value to the variable, and if you write only one variable without assigning a value, then Python does not think the variable is defined. As follows:

>>> a
traceback (most recent call last):
 File "<stdin>", line 1, in <module>
nameerror: Name ' A ' is not defined

Let's talk a little bit about variables, references, copying, and scoping issues in Python.

One, mutable objects & immutable objects

In Python, objects are divided into two types: mutable objects and immutable objects, immutable objects including Int,float,long,str,tuple, and variable objects including list,set,dict. It should be noted that the immutable meaning here is that the value is immutable. For variables of an immutable type, if you want to change a variable, a new value is created, the variable is bound to the new value, and the old value is waiting for garbage collection if it is not referenced. In addition, the immutable type can compute the hash value as the key of the dictionary. Variable type data when manipulating an object, there is no need to apply for memory elsewhere, just a continuous request (+ +) After this object, that is, its memory address will remain unchanged, but the area will grow or become shorter.

Here are some examples:

>>> a = ' xianglong.me '
>>> ID (a)
140443303134352
>>> a = ' 1saying.com
' >>> ID (a)
140443303131776
# After the value, the memory address of variable A has changed
# ' xianglong.me ' is str type, immutable, so assignment operation knowledge recreated str ' 1saying.com ' object, and then point the variable A to it


>>> a_list = [1, 2, 3]
>>> ID (a_list)
140443302951680
>>> a_list.append (4) After c13/>>>> ID (a_list)
140443302951680
# list is assigned a value, the memory address of the variable a_list does not change
# [1, 2, 3] is variable, The append operation only changed its value, and the variable a_list point did not change.

Two, variable type, object has type

Third, function value transfer

Let's look at one example:

Def func_int (a):
  a = 4
 
def func_list (a_list):
  a_list[0] = 4
 
t = 0
func_int (t)
print T
# output:0
 
t_list = [1, 2, 3]
func_list (t_list)
print t_list
# output: [4, 2, 3]

For the above output, many Python beginners are puzzled: The first example looks like a value, while the second example does pass the reference. In fact, it is also very easy to explain this problem, mainly because of the variable objects and immutable objects: for Mutable objects, the object does not reconstruct the object, and for the Mutable object, each action rebuilds the new object.

When a function parameter is passed, Python is actually assigning a reference to the object of the variable passed in the argument to the corresponding function internal variable. It is easier to understand by reference to the example above. The local variable "a" in the Func_int is actually another reference to the object that all the variable "T" refers to, because the integer object is immutable, so when the func_int modifies the variable "a", it actually converts the local variable "a" Point to the Integer object "1". So obviously, Func_list modifies a mutable object, and the local variable "a" and the global variable "t_list" point to the same object.

Four, shallow copy & deep copy

The next question is: What if we must copy a copy of a mutable object? Simple assignment has proved unworkable, so Python provides a copy module specifically for copying mutable objects. Copy has two methods: Copy () and Deepcopy (), the previous one is a shallow copy, the latter is a deep copy. A shallow copy duplicates only the first object that is passed to it, and the deep copy copies all the objects that can be copied. Here is an example:

A = [[1, 2, 3], [4, 5, 6]]
B = a
c = copy.copy (a)
d = copy.deepcopy (a)
 
a.append
a[1][2] = ten
 
P Rint a
print b
print c
print d
 
# [[1, 2, 3], [4, 5, ten],
# [[1, 2, 3], [4, 5,],
# [[ 1, 2, 3], [4, 5, Ten]]
# [[1, 2, 3], [4, 5, 6]]

V. Scope

When you create, change, or find a variable name in a Python program, you are in a place where you save the variable name, which we call the namespace. The term scope is also called a namespace. Specifically, the location of the variable name being assigned in the code (the variable declaration in Python is assigned, and the global declares only the domain of the variable's use) determines the range in which the variable can be accessed. function defines a local scope, and a module defines a global scope.

Each module is a global scope. That is, the variables created at the top level of the module file have global scope, and the external access becomes the property of a Module object. The scope of a global scope is limited to a single file. "Global" refers to the top-level variable name in a file that is global to this file. A new local scope is created each time a call to a function is made. Python also has recursion, that is, you can call itself, and each call creates five new local namespaces. The variable name of the assignment is a local variable unless declared as a global variable. If you need to assign a value within a function to the variable name at the top of the module file, you need to declare the variable inside the function through the global statement. All variables can be grouped into local, global, or built-in three species. The range is internal to Def, within the namespace of a module and the variables provided by the predefined __builtin__ modules.

Variable name references are divided into three scopes to find: first, locally, then within the function (if any), after the global, and finally the built-in. By default, a variable name assignment creates or alters a local variable. The global declaration assigns a value to the variable name that maps to the scope within the module file. Python's variable name resolution mechanism is also known as the LEGB Law, as follows:

When you use an indeterminate variable name in a function, Python searches for 4 scopes: The local scope (L), followed by the local scope (E) of def or lambda in the upper-layer nesting structure, followed by the global scope (G), and finally the built-in scope (B). Follow this search principle and stop where you found the first place. If it's not found, Python will complain. The following figure illustrates the search process (from inside and out):

It says that there are no types of variables in Python, but Python is really the type: all the variables in Python are a pointer to an object in memory, a reference to a value, and the type is followed by an object. To summarize: In Python, types are objects, not variables, variables and objects are separate, objects are entities in memory that store data, and variables are pointers to objects. In the book "Learning Python" There is a point of view: Variable type, object has a type, probably also say this meaning. Here is a diagram of the variable:

Python provides a global syntax like PHP, and a local variable of global definition becomes an alias for its corresponding global variable, which is the same variable. The following examples will help you better understand:

A = A-
 
def test1 ():
  a =
  print a
test1 () # output:
 
def test2 ():
  Global a
  print a
test2 () # Output: 44

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.