我想补充@Visionscaper在顶部所说的内容:
Third --> First --> object --> Second --> object
在这种情况下,解释器不会过滤掉对象类,因为它是重复的,而是因为第二类出现在层次结构子集中的头部位置而没有出现在尾部位置。而对象仅出现在尾部位置,在C3算法中不能将其视为确定优先级的强项。
C类的线性度(mro)为
- 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"
super()
有用的情况。我不建议将其与使用线性继承的类一起使用,因为这只是无用的开销。