Python 3.x Python中的闭包无效';sλ函数
考虑以下简短的代码片段:Python 3.x Python中的闭包无效';sλ函数,python-3.x,lambda,Python 3.x,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 lambda函数包含对s的引用,因此在for循环外部调用时
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
之所以发生这种情况,是因为
s
变量是一个引用,而不是一个值。引用值将在调用时解析,而不是在创建时解析。要在创建时解析该值,请使用默认参数
lambda s=s:打印
右侧可能重复,这是一个重复。非常感谢这个链接!您甚至可以使用x.f=lambda v=s:print(v)
交换def(v=s):print(v)