1. Function Scope Introduction
function scope
There are 4 types of function scopes in Python:
- l:local, local scope, which is the variable defined in the function:
- E:enclosing, the local scope of the nested parent function, which is the local scope of the ancestor function that contains the function, but is not global.
- G:global, global variables, variables defined at the module level, variables defined at the start of a module, outside of a function.
- B:built-in, the variables in the system fixed module, such as Int,bytearray.
The order of precedence for search variables is: local scope > Outer scope > Current module global scope > Python built-in scope, which is
L > E > G > B
Example Description:
2. Scope generation
In Python, only modules, classes, and functions (Def, Lambda) introduce new scopes, and other blocks of code (such as if, try, for, and so on) do not introduce new scopes, as in the following code:
- If 2 > 1:
- x = 2
- Print (x) #2
If does not introduce a new scope, X is still in the current scope, and the following code can be used.
- def test ():
- x = 2
- Print (x) # nameerror:name ' x ' is not defined
Def, class, and lambda can be introduced into a new scope.
3.global keywords
The Global and nonlocal keywords are used when the internal scope wants to modify the variables of the outer scope, and when the modified variable is on the global scope (the globally scope), use global first to declare the code as follows:
A def change_age (): Global ' before:%s'print (' modified:%s ' ' , age) Change_age () # Before modification:#修改后:
4. nonlocal keyword
The variables declared by the Global keyword must be on global scope, not nested scopes, and when you want to modify the variables in the nested scope (enclosing scope, outer non-global scope), you need to nonlocal the keyword.
Ten def inner (): nonlocal countprint (' Pre-modified:%s'print ( ' ' , Count) inner () print (count) outer () #修改前:#修改后:20 #
5. Summary:
(1) Variable lookup order: LEGB, scope local > Outer scope > Global >python Built-in scope in the current module;
(2) Only modules, classes, and functions can introduce new scopes;
(3) For a variable, the internal scope of the first declaration will overwrite the external variables, do not declare direct use, will use the external scope of the variable;
(4) Internal scope to modify the value of an external scope variable, the global variable uses the global keyword, the nested scope variable uses the nonlocal keyword, and nonlocal is the python3 new keyword.
Python Foundation-Variable Scope