请考虑以下简短代码段:
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
答案 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)