相同父亲的遗产和实例化中的一个

2024-10-02 14:25:36 发布

您现在位置:Python中文网/ 问答频道 /正文

我有两个类,它们来自一个普通的抽象类,即父类:

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

但是父对象不能修改子对象的值。我不知道为什么会这样。这可能是因为它们具有相同的继承类或相同的方法名?它没有意义,因为它们是具有不同实例化的不同对象


Tags: 对象selfidchilddatainitdeftable
1条回答
网友
1楼 · 发布于 2024-10-02 14:25:36

就像@Rawing在评论中所说的,它在How do I avoid having class data shared among instances?中得到了回答

问题是我没有初始化init定义中的数据变量。解决方法很简单:

class AbstractClass(object):
    data_table = ''

    def __init__(self, id, array):
         self.getFromId(id)
         self.data = [] # We have to initialize the variable in the init and not in the class
         self.data += array

(是的,我知道data=[]和data+=数组没有意义,但它是对实际问题的简化,所以我将保持原样:p)

谢谢

相关问题 更多 >