我想补充一下 @Visionscaper 在顶部所说的内容:
Third --> First --> object --> Second --> object
在这种情况下,解释器不会因为对象类重复而将其过滤掉,而是因为 Second 出现在层次结构子集的头部位置,而没有出现在尾部位置。而对象仅出现在尾部位置,在 C3 算法中不被视为确定优先级的强势位置。
C 类的线性化(mro),L(C),是
-
C类
-
加上合并
- linearisation of its parents P1, P2, .. = L(P1, P2, ...) and
- the list of its parents P1, P2, ..
线性合并是通过选择出现在列表头部而不是尾部的公共类来完成的,因为顺序很重要(下面会讲清楚)
第三个线性化可以按如下方式计算:
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"