1.经典MRO : 树形结构的深度遍历优先 - > 树形结构遍历
class A: pass class B(A): pass class C(A): pass class D(B, C): pass class E: pass class F(D, E): pass class G(F, D): pass class I: pass class J(B, C): pass class K(A): pass class H(I, J, K): pass class Foo(H, G): pass
流程图:
类的MRO: Foo -> H -> I-> J-> B-> A-> C-> K-> G-> F-> D-> E
2.新式类的MRO C3算法
class A:
pass
class B(A):
pass
class C(A):
pass
class D(B, C):
pass
class E(C, A):
pass
class F(D, E):
pass
class M:
pass
class N(M):
pass
class P(E, A):
pass
class X:
pass
class Q(P, N, X):
pass
class G(Q, F):
pass
class H(G, F):
pass
print(H.__mro__)
'''
(<class '__main__.H'>, <class '__main__.G'>, <class '__main__.Q'>, <class '__main__.P'>,
<class '__main__.F'>, <class '__main__.D'>, <class '__main__.B'>, <class '__main__.E'>,
<class '__main__.C'>, <class '__main__.A'>, <class '__main__.N'>, <class '__main__.M'>,
<class '__main__.X'>, <class 'object'>)
'''
C3算法:
L(H) = H + L(G) + L(F) + GF # HGQPFDBECANMX
L(G) = G + L(Q) + L(F) + QF # GQPFDBECANMX
L(Q) = Q + L(P) + L(N) + X + PNX # QPECANMX
L(P) = P + L(E) + A + EA # PECA
L(E) = E + L(C) + A + CA # ECA
L(C) = C + A + A # CA
L(N) = N + M # NM
L(F) = F + L(D) + L(E) + DE # FDBECA
L(D) = D + L(B) + L(C) + BC # DBCA
加法:merge(), 拿第一项的第一位和 后面每项的除了第一位比较. 如果没有出现, 则该位元素算出
如果出现了. 此时开始下一项的第一位继续和后面每一项的除了第一位比较:
中心思想:用头和后面身体比较