I know that super() and multi-inheritance have already been discussed here. But I did not find a solution, regarding my specific problem in python3. Let's assume we have:
#! /usr/bin/env python3
class A(object):
def __init__(self):
super().__init__()
def foo(self):
print("The")
class B(object):
def __init__(self):
super().__init__()
def foo(self):
print("world")
class C(B):
def __init__(self):
super().__init__()
def foo(self):
super().foo()
print("is")
class D(A,C):
def __init__(self):
super().__init__()
def foo(self):
super().foo()
print("nice")
d = D()
d.foo()
This will get me:
The
nice
On the other hand, if I change the order of inheritance in D() to:
class D(C,A):
def __init__(self):
super().__init__()
def foo(self):
super().foo()
print("nice")
It gives me
world
is
nice
I, however, only get the desired output:
The
world
is
nice
using:
class D(C,A):
def __init__(self):
super().__init__()
def foo(self):
A.foo(self)
C.foo(self)
print("nice")
Which I find quite unelegant.
So my question is: Is it possible to use super() in python3 invoking the super method of both super classes instead of just the first?
Maybe this will help
output:
Unfortunately, without a knowledge of the method resolution order (MRO) of
D
, there is no way to callsuper()
inD
to get at both base classes.But the MRO is powerful concept. In the second case,
the (MRO) is
Inasmuch as calling
super()
takes you to the next class in the MRO, as Mr. Pieters stated, and you want the print statements coming in the order ofA
,B
,C
, thenD
, simply putsuper().foo()
first andprint(...)
second in each definition offoo()
. The only exception is do not putsuper().foo()
in classA
becausefoo()
is not defined inobject
.Solution
Alternate solution
The MRO of
D(A,C)
in the first case includes all classes as well, so with correct ordering ofsuper()
andprint(...)
statements, one can make it work:Further reading
To understand inheritance order (e.g.
class D(C,A)
orclass D(A,C)
) and MRO, see https://www.python.org/download/releases/2.3/mro/. The C3 method resolution order is described in detail and there are nicely drawn ASCII class hierarchies with the MRO labeled.