多重继承的C3算法
O==Object
merge: ① 如果列表空则结束,非空 读merge中第一个列表的表头, ② 查看该表头是否在 merge中所有列表的表尾中。 ②-->③ 不在,则 放入 最终的L中,并从merge中的所有列表中删除,然后 回到①中 ②-->④ 在,查看 当前列表是否是merge中的最后一个列表 ④-->⑤ 不是 ,跳过当前列表,读merge中下一个列表的表头,然后 回到 ②中 ④-->⑥ 是,异常。类定义失败。
代码:
class D: def func(self): pass class E: def func(self): pass class F: def func(self): pass class B(D,E): def func(self): pass class C(E,F): def func(self): pass class A(B,C): def func(self): pass
print("从A开始查找:")
for s in A.__mro__:
print(s)
print("从B开始查找:")
for s in B.__mro__:
print(s)
print("从C开始查找:")
for s in C.__mro__:
print(s)
计算方式:
mro(A) = mro( A(B,C) )
原式= [A] + merge( mro(B),mro(C),[B,C] )
mro(B) = mro( B(D,E) )
= [B] + merge( mro(D), mro(E), [D,E] ) # 多继承
= [B] + merge( [D,O] , [E,O] , [D,E] ) # 单继承mro(D(O))=[D,O]
= [B,D] + merge( [O] , [E,O] , [E] ) # 拿出并删除D
= [B,D,E] + merge([O] , [O])
= [B,D,E,O]
mro(C) = mro( C(E,F) )
= [C] + merge( mro(E), mro(F), [E,F] )
= [C] + merge( [E,O] , [F,O] , [E,F] )
= [C,E] + merge( [O] , [F,O] , [F] ) # 跳过O,拿出并删除
= [C,E,F] + merge([O] , [O])
= [C,E,F,O]
原式= [A] + merge( [B,D,E,O], [C,E,F,O], [B,C])
= [A,B] + merge( [D,E,O], [C,E,F,O], [C])
= [A,B,D] + merge( [E,O], [C,E,F,O], [C]) # 跳过E
= [A,B,D,C] + merge([E,O], [E,F,O])
= [A,B,D,C,E] + merge([O], [F,O]) # 跳过O
= [A,B,D,C,E,F] + merge([O], [O])
= [A,B,D,C,E,F,O]
结果:
从A开始查找: <class '__main__.A'> <class '__main__.B'> <class '__main__.D'> <class '__main__.C'> <class '__main__.E'> <class '__main__.F'> <class 'object'> 从B开始查找: <class '__main__.B'> <class '__main__.D'> <class '__main__.E'> <class 'object'> 从C开始查找: <class '__main__.C'> <class '__main__.E'> <class '__main__.F'> <class 'object'>
如何快速判断查找规律?
- 从 “当前子类” 向上查找它的父类
-
2. 规律测试
实例2:
-
通过如下判断模式:
代码测试:
class A1: pass
class A2: pass
class A3: pass
class B1(A1,A2): pass
class B2(A2): pass
class B3(A2,A3): pass
class C1(B1): pass
class C2(B1,B2): pass
class C3(B2,B3): pass
class D(C1, C2, C3): passprint("从D开始查找:")
for s in D.__mro__:
print(s)print("从C3开始查找:")
for s in C3.__mro__:
print(s) - 测试结果:
-
从D开始查找: <class '__main__.D'> <class '__main__.C1'> <class '__main__.C2'> <class '__main__.B1'> <class '__main__.A1'> <class '__main__.C3'> <class '__main__.B2'> <class '__main__.B3'> <class '__main__.A2'> <class '__main__.A3'> <class 'object'> 从C3开始查找: <class '__main__.C3'> <class '__main__.B2'> <class '__main__.B3'> <class '__main__.A2'> <class '__main__.A3'> <class 'object'> Process finished with exit code 0
-
---------------------
作者:battlemage22
来源:CSDN
原文:https://blog.csdn.net/u011467553/article/details/81437780