Closed Package
Closures: Closures in Python are defined (interpreted) from the expression form as:
If in an intrinsic function, a reference is made to a variable that is in an outer scope (but not at the global scope), then the intrinsic function is considered a closure (closure).
Look at a function first:
def func1 () def func2 () a = 1 return a func2 ()
Because there are nested functions inside the function,
nested function definitions: functions defined inside cannot be called globally
So there's a closure problem.
What's the problem?
Is that func1 can't get FUNC2 's variable A.
How do you get it?
We know that a function is the first class of objects (the first kind of object you can use as a variable), you can put the variable in the FUNC1 (FUNC2) through return
def func1 () def func2 () a = 1 return a return func2 x = func1 () #这样就拿到了func2 and assigned to the variable x x () # x () equivalent to FUNC2 () See If you get a return value a so you get the FUNC2 variable a and if: def func1 (para1) para1 def func2 () A = 1 return para1 + a return Func2 func1 (5) #如果把5传给func1 will pack def FUNC2 this function, # Note: def func2 () a = 1 return 1 + a func1 (5) () #等同于func2 () #就变相调用函数func2 () Gets the return value of 6 print (FUNC1 (5 ) () # 6 #如果func1 (8), then Func2 packaged: def func2 () a = 1 return 8 + a #每次调用func1, It will return (package) A new closure instance so: closure = function + Reference environment
Python packet closure function