亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

Python在沒有多重繼承的情況下調用超級 - 每次都獲得一個新副本

Python在沒有多重繼承的情況下調用超級 - 每次都獲得一個新副本

飲歌長嘯 2021-10-05 16:26:36
我想利用多個子類共享同一個父類的能力。如何在不調用多重繼承的情況下執行此操作。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)


查看完整回答
反對 回復 2021-10-05
  • 1 回答
  • 0 關注
  • 235 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號