【发布时间】: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