1

Python 的 super() 如何与多重继承一起工作? 一个答案解释了为什么,对于这个例子:

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"

答案是:

>>> x = Third()
second
first
that's it

根据解释,这是因为:

内部调用__init__of ,因为这是 MRO 所规定的!First super(First, self).__init__()__init__Second

他什么意思?为什么调用 First super__init__会调用__init__Second?我认为First与Second无关?

据说:“因为这是 MRO 规定的”,我阅读了https://www.python.org/download/releases/2.3/mro/ 但仍然没有任何线索。

谁能解释一下?

4

1 回答 1

3

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".

于 2017-09-20T20:08:36.137 回答