user1187968
user1187968

Reputation: 8016

Python3 multiple inheritance: can call all super constructors at one sub constructor?

Is it possible in D's __init__ method, that I can call A, B, C's __init__? The following D class only calls 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)

Upvotes: 1

Views: 75

Answers (1)

Silvio Mayolo
Silvio Mayolo

Reputation: 70297

If you know all of the superclasses, you can call the methods explicitly.

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

We can even automate this using __mro__ to get all superclasses.

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

MRO stands for "method resolution order". It's a list of all of the classes in the inheritance hierarchy for the given class, in the order super() would see them. For your class D, it's [D, C, B, A, object]. We use [1:] to eliminate D from the list (as calling D.__init__ would cause infinite recursion).

Upvotes: 4

Related Questions