我想利用多個子類共享同一個父類的能力。如何在不調用多重繼承的情況下執行此操作。class Base(object): shared_thing = 'Hello' things = [] def __init__(self, message): self.things.append(message)class One(Base): def __init__(self, json_message): super(One, self).__init__(json_message)class Two(Base): def __init__(self, message): super().__init__(message)class Three(Base): def __init__(self, message): Base.__init__(self, message)one = One('one')print('ONE: ' + str(one.things))one = One('one but a second time')print('ONE: ' + str(one.things))two = Two('two')print('TWO: ' + str(two.things))three = Three('three')print('THR: ' + str(three.things))base = Base('base again')print('BAS: ' + str(base.things))但是,super的這三個不同的初始化會給我同一個對象的引用ONE: ['one']ONE: ['one', 'one but a second time']TWO: ['one', 'one but a second time', 'two']THR: ['one', 'one but a second time', 'two', 'three']BAS: ['one', 'one but a second time', 'two', 'three', 'base again']我沒有使用 python 獲得超級面向對象,所以如果這是錯誤的方法,請原諒。
1 回答

弒天下
TA貢獻1818條經驗 獲得超8個贊
您可能打算things像這樣設置為實例變量:
class Base(object):
shared_thing = 'Hello'
def __init__(self, message):
self.things = []
self.things.append(message)
添加回答
舉報
0/150
提交
取消