空字典作为python函数中的关键字参数的默认值:字典似乎不被初始化为{}在后续调用? [英] empty dictionary as default value for keyword argument in python function: dictionary seems to not be initialised to {} on subsequent calls?

查看:789
本文介绍了空字典作为python函数中的关键字参数的默认值:字典似乎不被初始化为{}在后续调用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是一个函数。我的目的是使用关键字参数默认值将字典设为空字典(如果未提供)。

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})

但是当我下一个调用f,我得到:

But when I next call f, I get:

>>> f(3)
(6, {2: 4, 3: 9})

看起来第二个调用中的关键字参数d不指向一个空字典,而是指向在上一个调用结束时留下的字典。每个电话号码x将重置为三个。

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.)

所以d的名称所指向的本地值应该被删除,而在下一个调用中,如果我不要提供关键字参数d,那么d应设置为 default {} 。但是正如你所看到的那样,d被设置在前面的调用中指向的字典中。

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.

发生了什么?

封闭范围内的def行中的 literal {}

Is the literal {} in the def line in the enclosing scope?

行为见于2.5,2.6和3.1。

This behavior is seen in 2.5, 2.6 and 3.1.

推荐答案

>>> def f(i, d=None, x=3):
...     if not d:
...         d={}
...     d[i] = i*i
...     x += i
...     return x,d
... 
>>> f(2)
(5, {2: 4})
>>> f(3)
(6, {3: 9})
>>> 

这篇关于空字典作为python函数中的关键字参数的默认值:字典似乎不被初始化为{}在后续调用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆