Guido在他的博客文章Method Resolution Order(包括之前的两次尝试)中详细介绍了这个问题。
在您的示例中,Third()将调用First.__init__。Python在类的父级中查找从左到右列出的每个属性。在这种情况下,我们正在寻找__init__。所以,如果你定义class Third(First, Second):
...
Python将从查看First开始,如果First没有属性,那么它将查看Second。
当继承开始交叉路径时(例如从Second继承的First),这种情况变得更加复杂。阅读上面的链接了解更多细节,但是简单地说,Python将尝试保持每个类在继承列表中出现的顺序,从子类本身开始。
例如,如果你有:class First(object):
def __init__(self):
print "first"
class Second(First):
def __init__(self):
print "second"
class Third(First):
def __init__(self):
print "third"
class Fourth(Second, Third):
def __init__(self):
super(Fourth, self).__init__()
print "that's it"
MRO是[Fourth, Second, Third, First].
顺便说一句:如果Python找不到一致的方法解析顺序,它将引发异常,而不是退回到可能让用户感到意外的行为。
编辑以添加不明确的MRO示例:class First(object):
def __init__(self):
print "first"
class Second(First):
def __init__(self):
print "second"
class Third(First, Second):
def __init__(self):
print "third"
Third的MRO应该是[First, Second]还是[Second, First]?没有明显的预期,Python将引发一个错误:TypeError: Error when calling the metaclass bases
Cannot create a consistent method resolution order (MRO) for bases Second, First
编辑:我看到一些人认为上面的示例缺少调用,所以让我解释一下:示例的重点是演示如何构造MRO。它们不是要打印“第一、第二、第三”或其他内容。当然,您可以——也应该——玩弄这个示例,添加super()调用,看看会发生什么,并深入了解Python的继承模型。但我在这里的目标是保持简单,并展示如何建立MRO。就像我解释的那样:>>> Fourth.__mro__
(,
, ,
,
)