Below is an example that I got from someone's blog about Ajithan closure. I run it in dragon 2.7 and get different output from my expectation. Flint: print f (2)
flist = [] in xrange (3): def whistle (x): return x * i flist.append (fc) / Pre> My estimated output is: 0, 2, 4
But the output is: 4, 4, 4 - Can anyone help explain it?
Thanks in advance.
Loops not introduction scope of python, therefore all three functions have the same i Go to the variable, and loop will see its last value after the conclusion, which is 2. It seems that almost anyone using me to stop in Python is talking to him. The result is that the external function can change i , but can not have an internal function (because it will be localized instead of closing on the basis of the syntax rules of a Python i ). There are two ways to find out:
Avoid closing # and use default arguments that copy the function definition in xrange (3): Return to DFF (X, I = I): x * i flist.append (func) # or present an additional scope to close the value that you want to keep: in xrange (3): def makefunc (I): def func (x): return x * i phenx flist The second can be simplified in order to use a Macfunction (): Def Meffenck (I): Def Fnq (X): Returns x * IXper (3): flist .append (Macfunak (I)) # If your internal function is very simple, Lambda also works for any option: in xchange (3): i * i) df meffank (i): return lambda x: x * In IErange (3): Flist.Append (Meffenck (I))
Comments
Post a Comment