Home > Article > Backend Development > Python nonlocal and global keyword parsing instructions
First of all, it must be clear that the nonlocal keyword is defined inside 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
See the difference? This is a function with another function nested inside it. When nonlocal is used, it is declared that the variable is not only valid
within the nested function inner(), but is valid within the entire large function.
Still the same, let’s look at an example:
x = 0 def 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 starts with variables in the entire environment Acts on variables of function class instead of on variables of function class.
The above is the detailed content of Python nonlocal and global keyword parsing instructions. For more information, please follow other related articles on the PHP Chinese website!