【问题标题】:Inheritance from same father and instantiation one in another [duplicate]从同一个父亲继承和实例化一个在另一个[重复]
【发布时间】:2017-10-04 14:00:17
【问题描述】:

我有这两个类,它们来自一个普通的抽象类,它将成为父类:

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,这是同样的问题。如果有人遇到同样的问题,我会写一个答案。
  • 不要写答案,请投票将其作为副本关闭。
  • def getParent 后面好像少了一个冒号。此外,return parentObject = ParentClass(id, ['e', 'f', 'g']) 行不是 Python AFAIK。你确定这段代码真的运行了吗?
  • 不,是我在真实代码中所做的简化示例。谢谢。

标签: python class inheritance instantiation


【解决方案1】:

就像@Rawing在cmets中说的,在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)

谢谢!!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-10-22
    • 1970-01-01
    • 2012-02-06
    • 2015-09-10
    • 2020-03-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多