为了账号安全,请及时绑定邮箱和手机立即绑定

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 关注
  • 223 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号