I am trying to understand how the super() method works. Here is the sample code I am using:
class A(object):
def __init__(self):
self.n = 'A'
def func(self):
print('@A')
self.n += 'A'
class B(A):
def __init__(self):
self.n = 'B'
def func(self):
print('@B')
self.n += 'B'
class C(A):
def __init__(self):
self.n = 'C'
def func(self):
print('@C')
super().func()
self.n += 'C'
class D(C, B):
def __init__(self):
self.n = 'D'
def func(self):
print('@D')
super().func()
self.n += 'D'
print(D.mro())
d = D()
d.func()
print(d.n)
The correct output results are:
[<class '__main__.D'>, <class '__main__.C'>, <class '__main__.B'>, <class '__main__.A'>, <class 'object'>]
DBCD
What I do not understand is why there is no A in the output? I thought when entering Class C, there is a super().func() which calls the func in Class A. However, it is not the case.
Can anyone help me understand this behavior?
Thank you!
>Solution :
No, each super().func() call lets you call func in the next class in the MRO of self (which may not be the same as the MRO of the current class). When you call C.func on an instance of D, you follow D‘s MRO and see that after C comes B.
B.func doesn’t call super, so the chain ends there, skipping A. If you want B.func to be useable in multiple inheritance situations, it needs to call super().func() too, like the other classes do.