python-C3算法

  • Post author:
  • Post category:python


  • 每一个类的继承顺序都是从父类向子类看
  • 形成一个指向关系的顺序[当前类]+[父类的继承顺序]
  • 如果一个类出现在从左到右的第一个顺序上并且没有出现在后面顺序中或者出现在后面的顺序中但是仍然是第一顺序,那么就把这个类提取出来

20190327153109.png

由上述可以知道B类,C类和D类是单继承,即很容易知道:

L(B)= [BFGO] L(C)=[CEO] L(D)=[DGO]

由此:

L(A) = L(B) +L(C) + L(D)
A = [BFGO]+[CEO]+[DGO]
AB = [FGO]+[CEO]+[DGO]
ABF = [GO]+[CEO]+[DGO]
ABFC = [GO]+[EO]+[DGO]
ABFCE = [GO]+[O]+[DGO]
ABFCED = [GO]+[O]+[GO]
ABFCEDG = [O]+[O]+[O]
ABFCEDGO
 #即顺序为:A->B->F->C->E->D->G->O

20190327154600.png

L(B)=[BDEO] L(C)=[CEFO]
L(A)=L(B) + L(C)
A = [BDEO]+[CEFO]
AB = [DEO]+[CEFO]
ABD = [EO]+[CEFO]
ABDC = [EO]+[EFO]
ABDCE = [O]+[FO]
ABDCEF = [O]+[O]
ABDCEFO
# 即顺序为:A->B->D->C->E->F->O

代码测试:

class D: pass
class E: pass
class F: pass
class B(D,E): pass
class C(E,F): pass
class A(B,C): pass


print(A.mro())
print(B.mro())
print(C.mro())
print(D.mro())

'''
[<class '__main__.A'>, <class '__main__.B'>, <class '__main__.D'>, <class '__main__.C'>, <class '__main__.E'>, <class '__main__.F'>, <class 'object'>]
[<class '__main__.B'>, <class '__main__.D'>, <class '__main__.E'>, <class 'object'>]
[<class '__main__.C'>, <class '__main__.E'>, <class '__main__.F'>, <class 'object'>]
[<class '__main__.D'>, <class 'object'>]

'''

20190327160915.png

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): pass

print(D.mro())
# D-C1-C2-B1-A1-C3-B2-B3-A2-A3-O
'''
[<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'>]
'''

20190327180109.png

class A(object):pass
class B(A):pass
class C(A):pass
class D(A):pass
class E(B):pass
class F(C):pass
class G(D):pass
class H(E,F,G):pass

print(H.mro())

"""
[<class '__main__.H'>, <class '__main__.E'>, <class '__main__.B'>, <class '__main__.F'>, <class '__main__.C'>, <class '__main__.G'>, <class '__main__.D'>, <class '__main__.A'>, <class 'object'>]
"""

转载于:https://www.cnblogs.com/yangchangjie150330/p/10608319.html