首页 > 解决方案 > Python 的 lambda 函数中的无效闭包

问题描述

考虑这个简短的代码片段:

class X:
    pass

xs = []
for s in ("one", "two", "three"):
    x = X()
    x.f = lambda: print(s)
    xs.append(x)

for x in xs:
    x.f()

它输出:

three
three
three

这真的是预期的行为吗?你能解释为什么这不是:

one
two
three

标签: python-3.xlambda

解决方案


您的 lambda 函数持有对 的引用s,因此在该 for 循环之外调用时会打印最后分配给 s 的值。尝试以下代码以获得您的预期行为。在这里,现有引用的副本作为函数参数s创建,v并且该值在函数内部打印f

class X:
    pass

xs = []
for s in ("one", "two", "three"):
    x = X()
    def f(v=s): print(v)
    x.f = f
    xs.append(x)

for x in xs:
    x.f()

输出:

one
two
three

推荐阅读