I have the following code:
class A:
def __init__(self):
print("A.__init__")
class B(A):
def __init__(self):
print("B.__init__")
super().__init__()
class C(A):
def __init__(self):
print("C.__init__")
super().__init__()
class D(B,C):
def __init__(self):
print("D.__init__")
super().__init__()
When I instantiate an object out of class D,
d = D()
I got:
>>> d = D()
D.__init__
B.__init__
C.__init__
A.__init__
Why did class A's __init__() only got called once, and at the very end? Note both class B and class C called class A's __init__(), so I expected that class A's __init__() should be called twice.
I read both Python 3's documentation and Mr. Hettinger's blog, but didn't figure out the underlying mechanism. So how does the super() determine that it only needs to execute once? Thanks.
super().__init__(), notA.__init__(). Why do you think thatA.__init__is the same thing in these cases?super()looks at the class MRO (method resolution order). For multiple inheritance (diamond inheritance graph) the MRO is still going to be linear, exactly to avoid callingA.__init__()more than once. Look atD.__mro__to see the actual MRO determined at runtime, you'll see it is[D, B, C, A]. Read the Python MRO documentation to see why and how.