Python - 类实例共享类字典变量?

时间:2018-06-01 08:02:10

标签: python-3.x class dictionary instance instance-variables

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

我已经玩了好几个小时但仍然无法绕过它。更改类DICT的一个实例的Student如何同步更改所有其他实例的DICT

这是如何发生的,如果我真的需要使用dict,解决此问题的最佳方法是什么?

2 个答案:

答案 0 :(得分:0)

您可以通过更改DICTNAME等类属性的初始化位置来实现所需的输出。 我会举个例子。

class Student():


    def __init__(self, name):
        self.DICT = {}
        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': 'Leo'}
Student two DICT: {'name': 'Liz'}
---------------------------------
Student one DICT: {'name': 'Tom'}
Student two DICT: {'name': 'Liz'}

在这里,您将检查字典值是否已更改。

答案 1 :(得分:0)

您正在混合类变量和实例变量。当你在构造函数之外声明一个变量时(即__init__)以上它是一个类变量,意味着它是共享的。相反,你只需要实例变量,如下所示。

class Student():
    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))