【问题标题】:Python Calling Super Without Multiple Inheritance - Get a new copy every time没有多重继承的 Python 调用 Super - 每次都获取一个新副本
【发布时间】:2019-01-07 23:30:20
【问题描述】:

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

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 获得超级面向对象,如果这是错误的方法,请原谅。

谢谢!

【问题讨论】:

  • 因为他们都使用Base.things,一个类变量。如果您希望每个实例使用不同的变量,请使用实例变量
  • __init__函数中使用self.things = []而不是父级中的things = []

标签: python object multiple-inheritance


【解决方案1】:

您可能打算像这样将things 设置为实例变量:

class Base(object):
    shared_thing = 'Hello'

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

【讨论】:

    猜你喜欢
    • 2018-12-08
    • 1970-01-01
    • 1970-01-01
    • 2014-07-01
    • 2017-07-30
    • 2016-02-25
    • 2021-11-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多