python - 在Python中访问多个对象中的字典时出现问题

标签 python class dictionary

我是一名 Python 新手,在理解 Python 中的字典如何工作方面遇到了一些问题。

我创建了一个类:

class Test:
    dictionary = dict()

    def __init__(self, id):
        self.id = id

    def add(self, key, val):
        self.dictionary[key] = val

    def print(self):
        print("id: " + str(self.id))
        print(self.dictionary.items())

我正在执行这段代码:

list = [Test(0), Test(1)]
list[0].add(0, 0)
list[1].add(1, 1)

for t in list:
    t.print()

这段代码想要的效果是得到:

id: 0
dict_items([(0, 0)])
id: 1
dict_items([(1, 1)])

但我得到的是:

id: 0
dict_items([(0, 0), (1, 1)])
id: 1
dict_items([(0, 0), (1, 1)])

为什么会发生这种情况?以及我应该怎样做才能达到预期的效果?尽管字典属于同一类的两个不同实例,但它似乎共享相同的内存。

最佳答案

那是因为 dictionary 是一个类属性。使其成为实例属性。

看看What is the difference between class and instance attributes? .

class Test:
    def __init__(self, id):
        self.id = id
        self.dictionary = dict()

关于python - 在Python中访问多个对象中的字典时出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53120538/

相关文章:

python - 为什么内置函数 `any(b'\x0 0')` 在 python2 和 python3 之间表现不同?

javascript - 在 JavaScript 中提升对象

javascript - 将 "this"的范围携带到内部函数中

c# - 从列表<Control>获取字典<string,string>

python - 使用日期时间键的字典搜索

python - 如何将输入读取为数字?

python - Mac OS X/bin/bash : python: command not found in some IDE

python - python : how? 中的类型转换类

Python:以值作为字典获取前n个键

python - 如何检查numpy矩阵的列中的所有值是否相同?