I have an array of functions, for example:
>>> def f():
... print "f"
...
>>> def g():
... print "g"
...
>>> c=[f,g]
Then i try to create two lambda functions:
>>> i=0
>>> x=lambda: c[i]()
>>> i+=1
>>> y=lambda: c[i]()
And then, call them:
>>> x()
g
>>> y()
g
Why c[i] in lambda are the same?
That's because the lambda function is fetching the value of the global variable i
at runtime:
>>> i = 0
>>> x=lambda z = i : c[z]() #assign the current value of `i` to a local variable inside lambda
>>> i+=1
>>> y =lambda z = i : c[z]()
>>> x()
f
>>> y()
g
A must read: What do (lambda) function closures capture?
In Python closures don't capture actual values, but instead they capture namespaces. So when you use i
inside your function it's actually looked up in the enclosing scope. And the value there has already changed.
You don't need all those lambda
s and lists to see this.
>>> x = 1
>>> def f():
... print(x)
...
>>> x = 2
>>> def g():
... print(x)
...
>>> g()
2
>>> f()
2
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.