【问题标题】:Python3 multiple inheritance: can call all super constructors at one sub constructor?Python3多重继承:可以在一个子构造函数中调用所有超级构造函数吗?
【发布时间】:2021-10-13 15:30:29
【问题描述】:

是否有可能在D's __init__ 方法中,我可以调用A, B, C's __init__?以下D类只调用C's __init__

class A:
    def __init__(self, a='a'):
        print("Constructor A")
        self.a = a

class B:
    def __init__(self, b='b'):
        print("Constructor B")
        self.b = b

class C:
    def __init__(self, c='c'):
        print("Constructor C")
        self.c = c

class D(C, B, A):
    def __init__(self):
        super().__init__()

    def run(self):
        return self.b

d = D()
print(d.run)

【问题讨论】:

  • 当然,如果要使用super()进行协作多重继承,则需要在所有构造函数中使用super()。请参阅super considered super 否则,请显式调用它们
  • @juanpa.arrivillaga 你能把你的建议写成代码作为答案吗?我对 oop 不是很熟悉,非常希望学习如何做到这一点。 PS。我不是op :)
  • @MuhdMairaj 有很多现有的问题,最好的办法是通读该链接,Python 核心贡献者对它的解释比我好得多。甚至还有一个很棒的 PyCon 演讲版本:youtube.com/watch?v=EiOglTERPEo

标签: python multiple-inheritance


【解决方案1】:

如果您知道所有超类,则可以显式调用方法。

class D(C, B, A):
  def __init__(self):
    A.__init__(self)
    B.__init__(self)
    C.__init__(self)

我们甚至可以使用__mro__ 自动执行此操作以获取所有超类。

class D(C, B, A):
  def __init__(self):
    for cls in self.__class__.__mro__[1:]:
      cls.__init__(self)

MRO 代表“方法解析顺序”。它是给定类的继承层次结构中所有类的列表,按照super() 看到它们的顺序。对于您的班级D,它是[D, C, B, A, object]。我们使用[1:] 从列表中消除D(因为调用D.__init__ 会导致无限递归)。

【讨论】:

  • Guido 本人对 MRO 的一些补充阅读 here 供任何对书呆子方面感兴趣的人使用...
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-04-21
  • 2014-09-02
  • 1970-01-01
  • 1970-01-01
  • 2015-06-29
  • 2012-10-16
  • 2012-01-31
相关资源
最近更新 更多