Closures (closure)
When a function internally defines a function, and the internal function applies an external function parameter or a local variable, when the intrinsic function is treated as the return value, the relevant parameters and variables are stored in the return function, and the result is called the closure
Example1:
1 defTest (*args):2 3 deftest_1 ():4RST =05 forIinchArgs#The parameters outside the function are used here6RST + =I7 returnrst8 returnTest_1#returns a function as a return value, with related parameters and variables stored in the returned function9 TenA = Test () One Print(A ())
This is a common closure.
Closures also have deceptive places.
Example2:
defcount (): FS= [] #A list is defined here. forIinchRange (1,4): #defines a function f #F is the structure of a closure deff ():returnI*i#It's not going to be calculated immediately when we return.fs.append (f)returnfsf1,f2,f3=count ()Print(F1 ())Print(F2 ())Print(F3 ())#9#9#9#[finished in 0.2s]#Why is it 999, the reason for this is that the return function references the variable i,#and I is not executed immediately, but isosceles three functions are returned in a unified execution#at this point I has become 3, and the final call returns to 3*3 .#
The above problem results in the following: When you return a closure, you cannot reference any of the loop variables
Workaround:
and set up a function outside.
Example3:
defcount2 (): FS= [] #A list is defined here. defF (i):#I passed in as a parameter defg ():returnI*i#I'll do it right here when I return. returng forIinchRange (1,4): Fs.append (f (i))returnfsf1,f2,f3=Count2 ()Print(F1 ())Print(F2 ())Print(F3 ())#1#4#9
Python function closure ()