在Lambdas中捕获值而不是引用 [英] Capturing Value instead of Reference in Lambdas
问题描述
I was slightly surprised by this example given by Eli Bendersky (http://eli.thegreenplace.net/2015/the-scope-of-index-variables-in-pythons-for-loops/)
>>> def foo():
... lst = []
... for i in range(4):
... lst.append(lambda: i)
... print([f() for f in lst])
...
>>> foo()
[3, 3, 3, 3]
但是,当我想到它时,这是有道理的-lambda捕获的是对i的引用,而不是i的值.
But when I thought about it, it made some sense — the lambda is capturing a reference to i rather than i's value.
解决这个问题的方法如下:
So a way to get around this is the following:
>>> def foo():
... lst = []
... for i in range(4):
... lst.append((lambda a: lambda: a)(i))
... print([f() for f in lst])
...
>>> foo()
[0, 1, 2, 3]
这似乎起作用的原因是,当将i提供给外部lambda时,外部lambda创建一个范围并取消引用i,将a设置为i.然后,返回的内部lambda保留对a的引用.
It appears that the reason that this works is that when i is provided to the outer lambda, the outer lambda creates a scope and dereferences i, setting a to i. Then, the inner lambda, which is returned, holds a reference to a.
这是正确的解释吗?
推荐答案
默认参数是捕获值的另一种方法:
Default param is an another way to catch a value:
lst.append(lambda i=i: i)
这篇关于在Lambdas中捕获值而不是引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!