This article introduces Pythonnonlocal and global keyword parsing description nonlocal
First, we need to clarify that the nonlocal keyword is defined in the closure. See the following code:
x = 0def 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 for declaration:
x = 0def 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
Have you seen the difference? This is another nested function in a function. When nonlocal is used, the variable is declared not only in the inner () nested function.
It is effective in the entire Big function.
Global
Let's look at an example:
x = 0def outer(): x = 1 def inner(): global x x = 2 print("inner:", x) inner() print("outer:", x)outer()print("global:", x)
Result
# inner: 2# outer: 1# global: 2
Global is used for variables in the entire environment, rather than for variables of function classes.
The above is the details of the explanation of Python nonlocal and global keywords. For more information, see other related articles in the first PHP community!