不明白python中的闭包问题
def a(b=[]):
b.append(1)
return b
print a()
print a()
突然我得到了一个包含 2 个元素的列表,但是如何呢? b 不应该每次都设置为空列表。
感谢您的帮助
def a(b=[]):
b.append(1)
return b
print a()
print a()
All of a sudden i got a list with 2 elems, but how? Shouldn't b be getting set to empty list every time.
Thanks for the help
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
默认参数仅在定义函数时计算一次。它从一次调用到下一次调用都保留相同的对象,这意味着相同的列表不断被追加。如果您想解决此问题,请使用默认值
None
并检查该值。Default arguments are only evaluated once, when the function is defined. It retains the same object from one invocation to the next, which means that the same list keeps getting appended to. Use a default value of
None
and check for that instead if you want to get around this.与闭包无关,至少与通常意义上的闭包无关。
b
的默认值不是“一个新的空列表”;它是“我在定义函数时刚刚创建的这个特定对象,并将其初始化为空列表”。每次不带参数调用该函数时,都会使用同一个对象。Nothing to do with closures, at least not in the usual sense.
The default value for
b
is not "a new empty list"; it is "this particular object which I just created right now while defining the function, initializing it to be an empty list". Every time the function is called without an argument, the same object is used.由于其他答案中给出的原因,更正后的版本是:
The corrected version, for the reasons given in other answers, is:
默认参数在定义函数时计算(一次),而不是每次调用时计算。
试试这个:
default arguments are evaluated (once) when the function is defined, not each time it is called.
try this: