in How does Python's super() work with multiple inheritance? one answer explains the reason why, for this example:
class First(object):
def __init__(self):
super(First, self).__init__()
print "first"
class Second(object):
def __init__(self):
super(Second, self).__init__()
print "second"
class Third(First, Second):
def __init__(self):
super(Third, self).__init__()
print "that's it"
the answer is:
>>> x = Third()
second
first
that's it
According to the explanation, it is because:
Inside
__init__
ofFirst
super(First, self).__init__()
calls the__init__
ofSecond
, because that is what the MRO dictates!
What does he mean? Why does calling First super __init__
will call __init__
of Second? I think First has nothing to do with Second?
It is said that: "because that is what the MRO dictates", I read https://www.python.org/download/releases/2.3/mro/ but still have no clue.
Can anybody explain?
It doesn't matter what the MRO (method resolution order) of the individual classes is. The only thing that matters (if you use super
) is the MRO of the class you call the method on.
So when you call Third.__init__
it will follow Third.mro
which is Third, First, Second, object
:
>>> Third.mro()
[__main__.Third, __main__.First, __main__.Second, object]
So any super
will look up the next superclass in the MRO, not the superclass of the actual class you're "in".