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


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如何同步更改StudentDICT所有其他实例。

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

您可以通过更改类属性(如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'}

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

您正在混合类变量和实例变量。当您在构造函数之外声明一个变量时(即上面__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))

相关内容

  • 没有找到相关文章

最新更新