我想补充一下@Visionscaper在开头说的话:
Third --> First --> object --> Second --> object
在这种情况下,解释器不会过滤掉对象类,因为它是重复的,而是因为Second出现在一个层次结构子集的头部位置,而不是尾部位置。而在C3算法中,对象只出现在尾部位置,不被认为是一个强位置来确定优先级。
线性化(mro)的类C, L(C),是
丙类
加上归并
线性化父函数P1, P2, ..= L(P1, P2,…
它的父元素P1, P2, ..
线性化合并是通过选择出现在列表头部而不是尾部的公共类来完成的,因为顺序很重要(下面会清楚地说明)
Third的线性化计算如下:
L(O) := [O] // the linearization(mro) of O(object), because O has no parents
L(First) := [First] + merge(L(O), [O])
= [First] + merge([O], [O])
= [First, O]
// Similarly,
L(Second) := [Second, O]
L(Third) := [Third] + merge(L(First), L(Second), [First, Second])
= [Third] + merge([First, O], [Second, O], [First, Second])
// class First is a good candidate for the first merge step, because it only appears as the head of the first and last lists
// class O is not a good candidate for the next merge step, because it also appears in the tails of list 1 and 2,
= [Third, First] + merge([O], [Second, O], [Second])
// class Second is a good candidate for the second merge step, because it appears as the head of the list 2 and 3
= [Third, First, Second] + merge([O], [O])
= [Third, First, Second, O]
因此,对于下面代码中的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"
很明显,这个方法将如何解决
Third.__init__() ---> First.__init__() ---> Second.__init__() --->
Object.__init__() ---> returns ---> Second.__init__() -
prints "second" - returns ---> First.__init__() -
prints "first" - returns ---> Third.__init__() - prints "that's it"