请看以下简短的代码片段:
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
为什么那不是实际结果?
请看以下简短的代码片段:
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
你的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
x.f = lambda v=s: print(v)
替换 def f(v=s): print(v)
。 - kalehmanns
是一个引用,而不是一个值。当引用被调用时,它所引用的值会被解析,而不是在创建时就被解析。要在创建时解析值,请使用 默认参数
。"最初的回答"lambda s=s: print(s)