Analyze a piece of code
def count (): FS = [] for I in range (1, 4): Def f (): Return i*i fs.append (f) Return FSF1 , F2, F3 = count ()
First say the bottom F1,F2,F3=COUNRT ()
F1, F2, F3 = count () equals [F1, F2, f3] = [F, F, F]
Equivalent to F1 = f
F2 = f
F3 = f
Fs.append (f)
Note here that the function f is added to FS instead of the value returned by F, you can try to execute the command:
>>> f<function F at 0x00000283bf7706a8>>>> count () [<function count.<locals>.f at 0x00000283bf770840>, <function count.<locals>.f at 0x00000283bf7707b8>, <function count.<locals >.F at 0x00000283bf770598>]
It is visible that a list of three functions is returned. So when executing code
F1, F2, F3 = count ()
, the three functions that count contains are assigned to F1, F2, F3, respectively, in index order, and i=3 at this time, so the function evaluates to 9.
>>> F1 () 9>>> F2 () 9>>> F3 () 9
In Python everything is the object, and the variable I only one, in three cycles, it points to the object changes, and the function f1,f2,f3 in the actual execution of the address I pointed to the actual storage data has become 3, so three times the result is the same.
Fs.append (f) Here the f is just a pointer is not a function so do not execute until when to execute so after the FOR loop 3 times I became 3 F always after all the execution is done before going to call because it is placed in the ""
No matter how many times it is called Count one of his for has been executed 3 times I has become 3 so at this time the F function used is of course 3
This article is from "Life is waiting for Gordo" blog, please make sure to keep this source http://chenx1242.blog.51cto.com/10430133/1769485
Analyze a closure function