Python:字典作为实例变量 [英] Python: Dictionary as instance variable

查看:166
本文介绍了Python:字典作为实例变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:

最少惊讶在Python中:可变默认参数

的字典作为Python 3中的类实例变量。我理解的方式是,Python中的实例变量具有每个实例存储,不像类变量是类的(类似于其他一些语言称为静态)。

I'm very confused about the behavior of dictionaries as class instance variables in Python 3. The way I understand it, instance variables in Python have per-instance storage, unlike class variables which are per-class (similar to what some other languages call "static").

这似乎是成立的,除非实例变量是从默认参数创建的字典。例如:

And this seems to hold true, except when the instance variable is a dictionary created from a default parameter. For example:

class Foo:
    def __init__(self, values = dict()):
        self.values = values

f1 = Foo()
f1.values["hello"] = "world"

f2 = Foo()
print(f2.values)

此程式输出:

{'hello': 'world'}

Huh?为什么实例 f2 有与 f1

Huh? Why does the instance f2 have the same dictionary instance as f1?

如果我不将一个空字典作为默认参数传递,我就得到了预期的行为,并且只需将 self.values 分配给一个空字典: / p>

I get the expected behavior if I don't pass in an empty dictionary as a default parameter, and just assign self.values to an empty dictionary explicitly:

class Foo:
    def __init__(self):
        self.values = dict()

但我不明白为什么会有什么区别。

But I can't see why this should make any difference.

推荐答案

这是Python中众所周知的惊喜。默认参数在定义函数时求值,而不是在调用时求值。所以你的默认参数是一个公共 dict 的引用。

This is a well known surprise in Python. The default parameters are evaluated when the function is defined, not when it is called. So your default parameter is a reference to a common dict. It has nothing to do with assigning it to class/instance variables.

如果要使用默认参数,请使用,并检查:

If you want to use a default parameter, use None, and check it:

if values is None:
    self.values = {}
else:
    self.values = values

这篇关于Python:字典作为实例变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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