不明白python中的闭包问题

发布于 2024-10-06 05:30:23 字数 153 浏览 0 评论 0原文

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

假扮的天使 2024-10-13 05:30:23

默认参数仅在定义函数时计算一次。它从一次调用到下一次调用都保留相同的对象,这意味着相同的列表不断被追加。如果您想解决此问题,请使用默认值 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.

夏雨凉 2024-10-13 05:30:23

与闭包无关,至少与通常意义上的闭包无关。

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.

明明#如月 2024-10-13 05:30:23

由于其他答案中给出的原因,更正后的版本是:

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

    b.append(1)
    return b

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
梦里的微风 2024-10-13 05:30:23

默认参数在定义函数时计算(一次),而不是每次调用时计算。

试试这个:

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

print a()
print a()

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()
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文