7

我在 python 解释器中尝试了以下代码:

>>> def say(n):
...   print n
... 
>>> say(12)
12
>>> test = []
>>> for each in range(30):
...   test.append(lambda: say(each))
... 
>>> test[0]()
29
>>> test[13]()
29

这看起来很奇怪,它不应该在最后两个调用中返回 0 和 13 吗?我试过直接看测试本身,它似乎所有的功能都是不同的

>>> test[0] == test[1]
False
>>> test[0]
<function <lambda> at 0x203e140>
>>> test[1]
<function <lambda> at 0x203e1b8>

知道为什么他们的行为都一样吗?

4

0 回答 0