我想用“无生命”来详细说明这个答案,因为当我开始阅读如何在Python的多重继承层次结构中使用super()时,我并没有立即得到它。
你需要了解的是super(MyClass, self).__init__()在完整继承层次结构的上下文中根据所使用的方法解析排序(MRO)算法提供下一个__init__方法。
理解这最后一部分至关重要。让我们再考虑一下这个例子:
#!/usr/bin/env python2
class First(object):
def __init__(self):
print "First(): entering"
super(First, self).__init__()
print "First(): exiting"
class Second(object):
def __init__(self):
print "Second(): entering"
super(Second, self).__init__()
print "Second(): exiting"
class Third(First, Second):
def __init__(self):
print "Third(): entering"
super(Third, self).__init__()
print "Third(): exiting"
根据Guido van Rossum关于方法解析顺序的文章,解析__init__的顺序是使用“深度优先的从左到右遍历”来计算的(在Python 2.3之前):
Third --> First --> object --> Second --> object
删除所有重复项后,除了最后一个,我们得到:
Third --> First --> Second --> object
那么,让我们来看看当我们实例化一个Third类的实例时会发生什么,例如x = Third()。
According to MRO Third.__init__ executes.
prints Third(): entering
then super(Third, self).__init__() executes and MRO returns First.__init__ which is called.
First.__init__ executes.
prints First(): entering
then super(First, self).__init__() executes and MRO returns Second.__init__ which is called.
Second.__init__ executes.
prints Second(): entering
then super(Second, self).__init__() executes and MRO returns object.__init__ which is called.
object.__init__ executes (no print statements in the code there)
execution goes back to Second.__init__ which then prints Second(): exiting
execution goes back to First.__init__ which then prints First(): exiting
execution goes back to Third.__init__ which then prints Third(): exiting
这详细说明了为什么实例化Third()会导致:
Third(): entering
First(): entering
Second(): entering
Second(): exiting
First(): exiting
Third(): exiting
从Python 2.3开始,MRO算法已经得到了改进,在复杂的情况下工作得很好,但我猜使用“深度优先的从左到右遍历”+“删除除最后一个重复项之外的重复项”在大多数情况下仍然有效(如果不是这样,请评论)。一定要阅读Guido的博客文章!