Python Variable Scope details

Source: Internet
Author: User
Tags class definition variable scope in python


  in Python, variable lookup follows the LGB principle of prioritizing a variable in a local scope (regional scope), failing to find it in the global scope, and finally attempting to build the scope again (build-in Scope), and throws an exception if it is still not found. Later, due to the appearance of closures and nested functions, the scope adds an external scope, so that the lookup scope priority of the variable becomes: local, external, global, and built-in. Scopes are produced by statements such as Def, class, and lambda, and if, try, and for statements do not produce new scopes. Let's look at one of the following examples:


The code is as follows

Def scope1_f1 ():
def f2 ():
Print Local_v
Local_v = ' Local '
F2 ()
Print Global_v

if __name__ = = "__main__":
Global_v = ' Global '
SCOPE1_F1 ()


In the SCOPE1_F1 function we do not assign a value to Global_str (that is, there is no variable lobal_str in the local scope of SCOPE1_F1), but the program normally outputs the result ' locals ' and ' global '.



Global variables should not be assigned to a local scope
It is important to note that while we can access global variables in a function, the Python interpreter will not look up from the global scope and throw a unboundlocalerror error once the global variable is assigned to the local scope. This rule is equally valid when it is looked up from a local scope to an external scope.


The code is as follows

Def scope1_f1 ():
Print Global_v
Global_v = ' Local '

if __name__ = = "__main__":
Global_v = ' Global '
SCOPE1_F1 ()


Run the program we will get: unboundlocalerror:local variable ' global_v ' referenced before assignment



It is not accurate to describe the rule as "a global variable in a local scope should be read-only". Because if the variable is of type list, we can modify the global variable by append this method without affecting the local scope's access to the variable.


The code is as follows

Def scope1_f1 ():
Print Global_v
Global_v.add (' local ')

if __name__ = = "__main__":
Global_v = [' Global ']
SCOPE1_F1 ()


To assign a global variable using the global implementation in a two-part scope



If you really need to assign a global variable, you should use global to modify the variable in a local scope. Global modification of variables in python2.6 can be done anywhere in the function, but the interpreter prompts syntaxwarning if the global is assigned a value.


The code is as follows

Def scope1_f1 ():
Global Global_v
Print Global_v
Global_v = ' Local '

if __name__ = = "__main__":
Global_v = ' Global '
SCOPE1_F1 ()


Three inheriting classes use variables in the first base class preferentially



In the absence of a variable initialization, the inheriting class takes precedence over the variables in the first base class. The following example prints 1 instead of 2. (Note: If the inheriting class is an initialization function, the initialization function of the first base class will be prioritized, and the initialization function for the base class will be adjusted if none of the preceding base classes are present, and the initialization function's modification of the variable is not covered in this article).


The code is as follows

Class Sclass1 ():
A = 1
def run (self):
Print SELF.A
Class Sclass2 ():
A = 2
def run (self):
Print SELF.A

Class Dclass (Sclass1, Sclass2):
def run (self):
Print SELF.A

if __name__ = = "__main__":
A = Dclass ()
A.run ()


The four global scopes refer to this module, not the program.



A variable lookup will only be made in the scope of this module, even if you use from XXX import * will not collapse the module lookup. Importing a module in Python can be understood as assigning another module variable to the same name as the current module, and assigning a variable to the current module does not affect the variable in the import module.


The code is as follows

main.py
From module2 Import *
if __name__ = = "__main__":
Module2_v = 5
MODULE2_V1 = 3
PRINT_MODUL2 ()

modul2.py
MODULE2_V1 = ' Module2 '
Def print_modul2 ():
Print MODULE2_V1
Print Module2_v


In Python everything is object and variable, so the lookup of functions, modules, and so on, follows the rules above.
Finally, there is the problem of using global to assign values to global variables in local scopes, so how do you assign values to external variables in a local scope? I have not found any other solution for the present, except to use the list as a reference, so stay here and think about it.



Python is a static scope language, although it is itself a dynamic language. That is, the scope of a variable in Python is determined by its location in the source code, which is similar to C, but the scope difference between Python and C is quite obvious.



Next, we'll talk about Python's scoping rules, which will also illustrate the difference between Python and C in terms of scope.



In Python 2.0 and earlier versions, Python supported only 3 scopes, the local scope, global scope, built-in scope, and in Python 2.2 python formally introduced a new scope---nesting scope; in Python 2.1, Nested scopes can be turned on as an option; the introduction of nested scopes is essentially Python's support for closures, and there are a lot of explanations on the web about closures, which are not covered in detail here. Accordingly, the variable lookup order is changed from previous LGB to LEGB (l:local,e:enclosing,g:global,b:built-in).



In Python, not every block of code can introduce a new scope, which is a lot different from C:


The code is as follows

#include <stdio.h>
int main () {
if (2 > 0) {
int i = 0;
}
printf ("I =%d", i);
return 0;
}


In this code, the IF clause introduces a local scope where the variable i exists in this local scope but is not externally visible, so the next reference to the variable i in the printf function throws a compilation error.



But that's not true in Python:


The code is as follows
If True:
i = 0


Print I in this code, the IF clause does not introduce a local scope, and the variable i is still in the global scope, so the variable i is visible for the next print statement.



In fact, in Python, only modules, classes, and functions introduce new scopes, and other blocks of code do not introduce new scopes.



In Python, you don't have to declare it beforehand before you use a variable, but before you actually use it, it must already be bound to an object, and the name binding will introduce a new variable in the current scope while shielding the variable with the same name in the outer scope, regardless of where the name binding occurs in the current scope.



def f ():
Print I
The results of the F () run will show: Nameerror:global name ' I ' is not defined. Python first looks for the variable i in the local scope of function f, finds the failure, then finds the variable I in the global scope and the built-in scope, still fails, and eventually throws the Nameerror exception.


The code is as follows
i = 0
def f ():
i = 8
Print I
F ()
Print I


The results show: 8 and 0. i = 8 is a name binding operation, which introduces a new variable i in the local scope of function f, shielding the global variable I, so the print statement inside F sees the local variable i,f the external print statement to see the global variable I.


The code is as follows
i = 0
def f ():
Print I
i = 0
F ()


The results of the operation show: unboundlocalerror:local variable ' i ' referenced before assignment. In this example, the variable i in function f is a local variable, but when the print statement uses it, it is not bound to any object, so it throws an exception.



Print I
i = 0 Whether it is run interactively or as a script file, the results are shown: nameerror:name ' I ' is not defined. The output here differs from the previous example because it is in the top-level scope (the module scope). For the module code, the code is not preprocessed before it executes, but for the function body, the code has been preprocessed before it runs, so it can be sensed regardless of where the name binding takes place in the scope. Python is a static scope language, but the name lookup does occur dynamically, so it is not until the runtime that the name problem is discovered.



In Python, a name binding introduces a new variable in the owning scope and binds to an object. A name binding occurs under several conditions:



1. Parameter declaration: The parameter declaration introduces a new variable in the local scope of the function;



2. Assignment operation: The initial assignment of a variable will introduce a new variable in the current scope, and subsequent assignment will rebind the variable;



3. Class and function definitions: class and function definitions introduce the class name and function names as variables into the current scope, and the class body and function body form another scope;



4.import statement: Import statement in the current scope of the introduction of new variables, generally in the global scope;



5.for statement: The For statement introduces a new variable (loop variable) in the current scope;



6.except statement: The except statement introduces a new variable (exception object) in the current scope.



In Python, the scope introduced by a class definition is not visible to a member function, which is very different from C + + or Java, so in Python the member function wants to refer to the variable defined by the class body, which must be referenced by self or by the class name.



The addition of nested scopes can cause some code to compile but or get different results, where the Python interpreter will help you identify the areas where this might be causing problems and give a warning.



The locals function returns all local variables, but does not return the variables in the nested scope, and no function returns the variables in the nested scope.




Globals (global variable)



Whether in other normal functions or class classes, they can be referenced directly by the corresponding variable names.



Local variable (automatic variable)



For functions within a function, including class classes, ordinary variables are automatic temporary variables



Here is the background:



Precedence Relationship of variables



The main difference between the scope of common local variables and global variables is:



Internal variables have precedence greater than external variables



In this case, the local variable (within the function) has a precedence greater than the (external) global variable



Other words:



A. If a variable with the same name as a global variable appears inside the function, it is a local variable;



B. If, within a function, there is no local variable of the same name, the corresponding variable is a global variable.



The priority of this variable is not only for the Python language, but also for almost every other language, such as c/c++/c# and so on.



So, the name in the __init__ in the example above is not a global variable:



Name = "Whole global name";



is the name of the local variable;



Where, this is the case that is specific to Python (and, or other special) languages, and can be used directly without declaring variables.



That is, the local variable name is not declared, but it is used directly, by:



name = Newpersionname;



In initialization, set to the corresponding name, here is "Crifan".



Variables for classes (class)



class, within the scope of the class, only through the



ClassName.PropertyName



Or that



Classname.variablename



To access the variables of the current class classname PropertyName



In the example, is through



Person.name



To access the value of the variable name in the class person.



Variable for example (Instance)



The variables in the example, in theory, are



Instanceobject.propertyname



To visit.



And here, because of the default, custom notation in Python, the name of the first parameter of a class's function is defined as the instance variable, and the name self, so it becomes:



Self. PropertyName



Up.



So, in the class function, you want to access the instance variable by



Self.name, to access the variable name in the example self of class person.



What are global variables and local variables



Outside the function, a section of code begins with a variable that is assigned a value, which can be referenced by multiple functions, which is the global variable;
The variable name defined within the function can only be referenced within the function, and cannot be used to refer to the variable name, the scope of which is local, also called as local variable;



If the variable name within the function is the same as the variable name outside the function, no conflict occurs. Like the following:
x = 100



def func ():
x = 55
x = 100 The variable x created by this assignment statement, the scope is a global variable;
x = 55 The variable x created by this assignment statement, the scope of which is a local variable and can only be used within the function func ().



Although the two variable names are the same, its scope distinguishes them. Scopes can also play a role in preventing variable name conflicts in a program, but it's better to try to avoid this if you're playing snake net Python beginners.



Summarize



1, the scope of the variable is determined by the location where the code is assigned
2, the variable can be in 3 different places, corresponding to 3 different scopes:
(a) A variable is assigned within the function, and its scope is positioned within the function
(b) When a variable is assigned in a nested function, this variable is non-local for this nested function
(c) The variable is assigned outside the function, which is the global variable of the current entire file


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.