This article mainly introduces to you the relevant information about the declaration and analysis of the keywords nonlocal and global in Python. The introduction in the article is very detailed. I believe it has certain reference value for everyone. Friends who need it can read it together. Take a look.
1. Global and nonlocal declarations in Python
The following code
a = 10 def foo(): a = 100
execute foo( ) Result a is still the assignment to the
variable
function. The variable is always bound to the local namespace of the function. , use the global statement to change this behavior.
>>> a 10 >>> def foo(): ... global a ... a = 100 ... >>> a 10 >>> foo() >>> a 100
When parsing a name, first check the local scope, and then check the scope defined by the external nested function layer by layer from the inside out. If it cannot be found Search Global command space and built-in Namespaces.
Although you can look up variables layer by layer, but! ..python2 only supports the innermost scope (local variables) and the global command space (gloabl), that is to sayInternal functionYou cannot reassign local variables defined in external functions. For example, the following code does not work.
def countdown(start): n = start def decrement(): n -= 1
In python2, the solution can be to put the modified value into a list or dictionary In python3, you can use the nonlocal statement to complete the modification
def countdown(start): n = start def decrement(): nonlocal n n -= 1
2. Python nonlocal and global keyword analysis
nonlocal
First of all, it must be clear that the nonlocal keyword is defined in the closure. Please look at the following code:
x = 0 def outer(): x = 1 def inner(): x = 2 print("inner:", x) inner() print("outer:", x) outer() print("global:", x)
Result
# inner: 2 # outer: 1 # global: 0
Now, add the nonlocal keyword to the closure to declare:
x = 0 def outer(): x = 1 def inner(): nonlocal x x = 2 print("inner:", x) inner() print("outer:", x) outer() print("global:", x)
Result
# inner: 2 # outer: 2 # global: 0
Do you see the difference? This is a function nested inside a function. When using nonlocal, it is declared that the variable is not only valid in the nested function inner(), but is valid in the entire large function.
global
x = 0 def outer(): x = 1 def inner(): global x x = 2 print("inner:", x) inner() print("outer:", x) outer() print("global:", x)
# inner: 2 # outer: 1 # global: 2
Summary
[Related recommendations]1. 2.Python basic introductory tutorial
3.Python meets data collection video tutorial
The above is the detailed content of Detailed analysis of nonlocal and global. For more information, please follow other related articles on the PHP Chinese website!