简体   繁体   English

不了解python中的闭包问题

[英]do not understand closures question in python

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? 我突然得到了一张2元的名单,但是如何? Shouldn't b be getting set to empty list every time. 不应该每次都被设置为空列表。

Thanks for the help 谢谢您的帮助

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. 使用默认值None ,如果你想解决这个问题,请检查它。

Nothing to do with closures, at least not in the usual sense. 与闭合无关,至少不是通常意义上的闭合。

The default value for b is not "a new empty list"; b的默认值不是“新的空列表”; 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: 由于其他答案中给出的原因,更正后的版本是:

def a(b=None):
    b = [] if b is None else b

    b.append(1)
    return b

default arguments are evaluated (once) when the function is defined, not each time it is called. 定义函数时,不会在每次调用函数时评估(一次)默认参数。

try this: 试试这个:

def a(b=None):
    if b is None
        b = []     
    b.append(1)
    return b

print a()
print a()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM