Variable value changes referenced in the python Closure
The closure feature of python is that the returned function also references the local variables of the outer function. Therefore, to correctly use the closure, make sure 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, and f3 values are all 9, because f () in the count () function obtained in this line: 1f1, f2, f3 = count () the I in the function has been iterated to 3, and the final result can only be 9 9 9. In the code given at the beginning, f1, f2, and f3 actually get a sequence, the variable in the outer function of the closure referenced when calculating each element in this sequence changes with iteration, from 1 to 3, at the same time, the element values obtained from this iteration are appended to the sequence and returned. The final result of Gu is 1 4 9.