I have read Expert Python Programming which has an example for multi-inheritance. The book author has explained but I did not understand it, so I would like to have another view.
The example shows that object B is created two times!
Could you please give me an intuitive explanation.
In [1]: class A(object):
...: def __init__(self):
...: print "A"
...: super(A, self).__init__()
In [2]: class B(object):
...: def __init__(self):
...: print "B"
...: super(B, self).__init__()
In [3]: class C(A,B):
...: def __init__(self):
...: print "C"
...: A.__init__(self)
...: B.__init__(self)
In [4]: print "MRO:", [x.__name__ for x in C.__mro__]
MRO: ['C', 'A', 'B', 'object']
In [5]: C()
C
A
B
B
Out[5]: <__main__.C at 0x3efceb8>
The book author said:
This happens due to the
A.__init__(self)call, which is made with the C instance, thus makingsuper(A, self).__init__()callB's constructor
The point from which I didn't get its idea is how A.__init__(self) call will make super(A, self).__init__() call B's constructor
superin C's init method?supercall as meaning 'call the next method in the MRO', rather than 'call my parent class's method', then this behaviour should make more sense. In this case, the reason you see B printed twice is because super already arranges for B's init to be called (by A's init), and so when you explicitly call B.init from C, you get a second call.__init__function is called twice but the object was already created before that.