Python's Closed Package the feature 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 cannot be changed after the function returns .
As follows:
def count (): FS = [] for I in range (1, 4): Def Lazy_count (j): Def Cou (): Return j*j return cou r = Lazy_count (i) Fs.append (R) return FSF1, F2, F3 = count () print F1 (), F2 (), F3 ()
If the above code is written as follows:
def count (): FS = [] for I in range (1, 4): Def f (): Return i*i fs.append (f) Return FSF1 , F2, F3 = count ()
The final F1, F2, F3 are all 9, because this line:
F1, F2, F3 = count ()
The f () function in the resulting count () function has been iterated to 3 and the final result can only be 9 9 9
In the code that was just given, F1,f2,f3 actually got a sequence, and the variables in the enclosing function that were referenced during each element of the sequence were changed from 1 to 3 in the iteration, and the element value of the iteration was calculated append the return of the input sequence, and the final result was 1 4 9.
This article is from the "Keep_study_zh" blog, make sure to keep this source http://zhkpsty.blog.51cto.com/9013616/1695120
Variable value change issues referenced in Python closures