Python multiple inheritance confusion [duplicate]
Solution 1:
Every __init__
is not run, because you didn't use super
properly. When designing a class hierarchy that uses super
, it's important that all the classes use it.
class One:
def __init__(self):
super().__init__()
print("One runs")
self.one = 1
class Two:
def __init__(self):
super().__init__()
print("Two runs")
self.two = 2
class Three(One, Two):
def __init__(self):
super().__init__()
print("Three runs")
While the inheritance graph is a directed acyclic graph, the method resolution order is a linear ordering of the nodes in that tree. super
uses that list, not the graph itself, when determining which method gets called via super()
.
>>> Three.mro()
[<class '__main__.Three'>, <class '__main__.One'>, <class '__main__.Two'>, <class 'object'>]
Three()
calls Three.__init__
, which calls One.__init__
, which calls Two.__init__
, which calls object.__init__
, which calls nothing because object.__init__
is the top of the chain for __init__
.
More detail can be found in Python's super()
considered super!, which also provides advice on how to adapt One
and Two
when they don't already use super
.