我有两个类,它们来自一个普通的抽象类,即父类:
class AbstractClass(object):
data_table = ''
data = []
def __init__(self, id, array):
self.getFromId(id)
self.data += array
def getFromId(self, id):
#Get data from the 'data_table' and init its values
...
class ParentClass(AbstractClass):
data_table = 'table_parent'
def __init__(self, id, array):
super(ParentClass, self).__init__(id, array)
class ChildClass(AbstractClass):
data_table = 'table_child'
def __init__(self, id, array):
super(ChildClass, self).__init__(id, array)
def getParent(self):
return parentObject = ParentClass(id, ['e', 'f', 'g'])
问题是,当我在对象子对象中调用child.getParent()时,元素数组正由父对象写入。例如,我们有这样一个电话:
>>> child = ChildClass('1234', ['a', 'b', 'c'])
>>> print(child.data)
['a', 'b', 'c']
>>> child.getParent()
>>> print(child.data)
['a', 'b', 'c', 'e', 'f', 'g']
但是父对象不能修改子对象的值。我不知道为什么会这样。这可能是因为它们具有相同的继承类或相同的方法名?它没有意义,因为它们是具有不同实例化的不同对象
就像@Rawing在评论中所说的,它在How do I avoid having class data shared among instances?中得到了回答
问题是我没有初始化init定义中的数据变量。解决方法很简单:
(是的,我知道data=[]和data+=数组没有意义,但它是对实际问题的简化,所以我将保持原样:p)
谢谢
相关问题 更多 >
编程相关推荐