Python的lambda函数中的无效关闭

时间:2019-06-28 11:41:31

标签: 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

2 个答案:

答案 0 :(得分:2)

您的lambda函数保留对public class CaseWorkNote : FullAuditedEntity { [ForeignKey("CaseId")] [Required] public virtual Case Case { get; private set; } public virtual Guid CaseId { get; private set; } /* Added */ [Required] public virtual string Text { get; set; } private CaseWorkNote() : base() { } public static CaseWorkNote Create(Case kase, string text) { return new CaseWorkNote() { Case = kase, Text = text }; } } 的引用,因此,在for循环之外调用时,会打印s的最后一个赋值。请尝试以下代码以达到预期的效果。在此,在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()

答案 1 :(得分:2)

发生这种情况是因为s变量是一个引用,而不是一个值。并且按引用的值将在调用而不是创建时解析。要在创建时解析值,请使用default argument

lambda s=s: print(s)