Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/16.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 3.x Python中的闭包无效';sλ函数_Python 3.x_Lambda - Fatal编程技术网

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)