firstly, let me quote a bit an essay from “Expert Python Programming” book:
In the following example, a C class that calls its base classes using the __init__ method will
make B class be called twice!
class A(object):
def __init__(self):
print "A"
super(A, self).__init__()
class B(object):
def __init__(self):
print "B"
super(B, self).__init__()
class C(A,B):
def __init__(self):
print "C"
A.__init__(self)
B.__init__(self)
print "MRO:", [x.__name__ for x in C.__mro__] #prints MRO: ['C', 'A', 'B', 'object']
C() #prints C A B B
and finally, here is an explanation of what’s going on here:
This happens due to the A.__init__(self) call, which is made with the C instance,
thus making super(A, self).__init__() call B’s constructor. In other words,
super should be used into the whole class hierarchy. The problem is that sometimes
a part of this hierarchy is located in third-party code.
i have no idea why “super(A, self).__init__() calls B’s constructor”. Please explain this moment. Thanks a lot.
The documentation for
supersays that:When you execute
A.__init__(self)from withinCthesuper(A, self)will return<super: <class 'A'>, <C object>>. As the instance isC(<C object>) all the classes in C’s inheritance hierarchy are picked up. And the__init__call is issued on all of them. Consequently you see ‘B’ getting called twice.To verify this add another class ‘Z’ and let ‘C’ inherit from ‘Z’ as well. See what happens.
In this case,
Awill callBandZ.Bwill callZas well.