Python scope, local and global variables
First understand that Python can change the scope of the code snippet is def class Lamda If/elif/else try/except/finally for/while
The search path for a variable is: local variable-global variable
Try the following code:
x=100def Main (): x+=1 print(x) main ()
When running the above code, there will be an error, for what, you need to understand the scope, local variables and the difference between the global variables
x=100def Main (): Global x x+=1 print(x) main () Print (x) #全局变量已被改变
Operation Result: 101101
Because we have added global X, the main () function is able to access the global variable x,
Python closures
Here we have a basic understanding of the Python scope rules
Let's write a closure.
# Python 3.5 def Inc (): #inc是外围函数 x=0 def Inner (): #inner is a nested function nonlocal x x+=1 print(x) return innerinc1=Inc () INC2 =Inc () INC1 () inc1 () inc1 () Inc2 ()
Run Result:1231
From this example, the intrinsic function is returned directly as a return value, where inc1 is a closure, which is essentially a function, consisting of two parts, a inner function and a variable x, and a closure that keeps the values of these variables in memory.
Why use closures?
Closures avoid the use of global variables, and closures can correlate functions with some of the data they manipulate.
"Life is short, Python is a song"--python Functional programming.