The inner layer function refers to the variable of the outer function (parameter also the variable), and then returns the case of the inner layer function, called the closure (Closure). The feature of closures is that the returned function also refers to the local variables of the outer function, so to properly use closures, it is necessary to ensure that the referenced local variables do not change after the function returns.
example: you want to return 3 functions at a time, calculate 1x1,2x2,3x3 separately:
def Count ():
fs = []
for I in range (1, 4):
def f ():
return i*i
fs.append (f)
print (FS)
return FS
F1, F2, F3 = count ()
Print (F1 (), F2 (), F3 ())
# The results are all 9. The reason is that when the count () function returns 3 functions, the value of the variable I referenced by these 3 functions has become 3.
# because F1, F2, F3 are not called, so they do not calculate i*i at this time, when F1 is invoked: 9.
# Therefore, the return function does not refer to any loop variables, or to subsequent variables that change.
The return closure cannot refer to a loop variable, please rewrite the count () function to correctly return a 1x1, 2x2, 3x3 function that can be computed.
def count1 ():
fs = []
For I in range (1, 4):
def F (j):
def g ():
return j*j
return G
result = f (i)
fs.append (Result)
print (FS)
return FS
A1, A2, a3 = Count1 ()
Print (A1 (), A2 (), A3 ())
Python Functional Programming (3)--closures