【发布时间】:2018-11-11 07:41:24
【问题描述】:
class Student():
NAME = ''
DICT = {}
def __init__(self, name):
self.NAME = name
self.DICT['name'] = name
def change_DICT(self, change):
self.DICT['name'] = change
student_one = Student('Leo')
student_two = Student('Liz')
print ('Student one NAME: ' + student_one.NAME)
print ('Student two NAME: ' + student_two.NAME)
print ('---------------------------------')
print ('Student one DICT: ' + str(student_one.DICT))
print ('Student two DICT: ' + str(student_two.DICT))
print ('---------------------------------')
student_one.change_DICT('Tom')
print ('Student one DICT: ' + str(student_one.DICT))
print ('Student two DICT: ' + str(student_two.DICT))
>> Student one NAME: Leo
>> Student two NAME: Liz
>> ---------------------------------
>> Student one DICT: {'name': 'Liz'}
>> Student two DICT: {'name': 'Liz'}
>> ---------------------------------
>> Student one DICT: {'name': 'Tom'}
>> Student two DICT: {'name': 'Tom'}
我已经玩了几个小时了,但仍然无法理解它。更改Student 类的一个实例的DICT 如何同步更改所有其他实例的DICT。
这是怎么发生的?如果我真的需要使用dict,解决这个问题的最佳方法是什么?
【问题讨论】:
-
除了我的回答:我确实觉得很奇怪
self.DICT仍然可以针对该类变量,所以我不确定为什么会发生这种情况。也许其他人可以启发我们。 -
@BramVanroy
self.DICT不针对该类变量,但self.DICT['name']可以。即使使用预定义的DICT,您的代码也能正常工作。谢谢你的帮助!我会将此标记为重复,因为我在@Cyber Tailor 建议的帖子中找到了我需要的内容。
标签: python-3.x class dictionary instance instance-variables