我是 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)])
为什么会发生这种情况?我该怎么做才能达到预期的效果?尽管字典属于同一类的两个不同实例,但它似乎共享相同的内存。
相关分类