空字典作为 python 函数中关键字参数的默认值:字典似乎在后续调用中没有初始化为 {} ?
这是一个函数。我的目的是使用关键字参数默认值使字典成为空字典(如果未提供)。
>>> def f( i, d={}, x=3 ) :
... d[i] = i*i
... x += i
... return x, d
...
>>> f( 2 )
(5, {2: 4})
但是当我下次调用 f 时,我得到:
>>> f(3)
(6, {2: 4, 3: 9})
看起来第二次调用中的关键字参数 d 并不指向空字典,而是指向前一个调用末尾留下的字典。每次调用时,数字 x 都会重置为 3。
现在我可以解决这个问题,但我希望您帮助理解这一点。我相信关键字参数位于函数的本地范围内,并且一旦函数返回就会被删除。 (如果我不精确,请原谅并纠正我的术语。)
因此应该删除名称 d 指向的本地值,并且在下次调用时,如果我不提供关键字参数 d,则 d 应设置为默认{}
。但正如您所看到的,d 被设置为 d 在前面的调用中指向的字典。
到底是怎么回事?
def 行中的 literal {}
是否位于封闭范围内?
此行为在 2.5、2.6 和 3.1 中可见。
Here's a function. My intent is to use keyword argument defaults to make the dictionary an empty dictionary if it is not supplied.
>>> def f( i, d={}, x=3 ) :
... d[i] = i*i
... x += i
... return x, d
...
>>> f( 2 )
(5, {2: 4})
But when I next call f, I get:
>>> f(3)
(6, {2: 4, 3: 9})
It looks like the keyword argument d at the second call does not point to an empty dictionary, but rather to the dictionary as it was left at the end of the preceding call. The number x is reset to three on each call.
Now I can work around this, but I would like your help understanding this. I believed that keyword arguments are in the local scope of the function, and would be deleted once the function returned. (Excuse and correct my terminology if I am being imprecise.)
So the local value pointed to by the name d should be deleted, and on the next call, if I don't supply the keyword argument d, then d should be set to the default {}
. But as you can see, d is being set to the dictionary that d pointed to in the preceding call.
What is going on?
Is the literal {}
in the def line in the enclosing scope?
This behavior is seen in 2.5, 2.6 and 3.1.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)