Python在没有多重继承的情况下调用超级-每次获取一个新副本

时间:2019-01-07 23:30:20

标签: python object multiple-inheritance

我想利用多个子类共享同一父类的能力。如何在不调用多重继承的情况下做到这一点。

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 个答案:

答案 0 :(得分:1)

您可能已经打算将things设置为实例变量,如下所示:

class Base(object):
    shared_thing = 'Hello'

    def __init__(self, message):
        self.things = []
        self.things.append(message)