在 Lambda 中捕获值而不是引用 [英] Capturing Value instead of Reference in Lambdas
问题描述
Eli Bendersky 给出的这个例子让我有点惊讶(http://eli.thegreenplace.net/2015/the-scope-of-index-variables-in-pythons-for-loops/)
<预><代码>>>>定义 foo():... lst = []...对于范围内的我(4):... lst.append(lambda: i)... 打印([f() for f in lst])...>>>富()[3, 3, 3, 3]但是当我考虑它时,它是有道理的——lambda 正在捕获对 i 的引用,而不是 i 的值.
解决这个问题的方法如下:
<预><代码>>>>定义 foo():... lst = []...对于范围内的我(4):... lst.append((lambda a: lambda: a)(i))...打印([f() for f in lst])...>>>富()[0, 1, 2, 3]看起来这样做的原因是当 i 被提供给外部 lambda 时,外部 lambda 会创建一个范围并取消引用 i,将 a 设置为 i.然后,返回的内部 lambda 持有对 a 的引用.
这是正确的解释吗?
默认参数是另一种捕获值的方法:
lst.append(lambda i=i: i)
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]
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]
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.
Is this a correct explanation?
Default param is an another way to catch a value:
lst.append(lambda i=i: i)
这篇关于在 Lambda 中捕获值而不是引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!