python 菱形继承问题究极版
如果只是正常的菱形继承,经典类(python2中最后一个父类不继承object类)是深度优先,即会从左边父类开始一路走到底
新式类(最后一个父类继承了object类)是广度优先,即从左边父类开始继承,留着最后一个类不继承
# 此处只打印新式类正常菱形继承时的顺序,python2中经典类的顺序是F->D->B->A->E->C
1 class A(object): 2 pass 3 4 5 class B(A): 6 pass 7 8 9 class C(A): 10 pass 11 12 13 class D(B): 14 pass 15 16 17 class E(C): 18 pass 19 20 21 class F(D, E): 22 pass 23 24 25 print(F.mro()) 26 27 # 输出 28 ''' 29 [<class '__main__.F'>, <class '__main__.D'>, <class '__main__.B'>, <class '__main__.E'>, <class '__main__.C'>, <class '__main__.A'>, <class 'object'>] 30 '''
如果是不正常的菱形继承,即最后两个类继承了两个相同的父类,但是父类顺序不同则会报错,此处是A,G互换
1 class G(object): 2 pass 3 4 5 class A(object): 6 pass 7 8 9 class B(A, G): # 此处继承顺序是A,G 10 pass 11 12 13 class C(G, A): # 此处继承顺序是G,A 14 pass 15 16 17 class D(B): 18 pass 19 20 21 class E(C): 22 pass 23 24 25 class F(D, E): 26 pass 27 28 29 print(F.mro()) 30 31 # 输出 32 ''' 33 Traceback (most recent call last): 34 File "C:/test.py", line 23, in <module> 35 class F(D,E): 36 TypeError: Cannot create a consistent method resolution 37 order (MRO) for bases A, G 38 '''
如果继承两个相同的父类,但是顺序相同,会和你想的一样,如果两者继承的都是A,G,打印顺序会是先A,后G.
1 class G(object): 2 pass 3 4 5 class A(object): 6 pass 7 8 9 class B(A, G): # 此处继承顺序是A,G 10 pass 11 12 13 class C(A, G): # 此处继承顺序是A,G 14 pass 15 16 17 class D(B): 18 pass 19 20 21 class E(C): 22 pass 23 24 25 class F(D, E): 26 pass 27 28 29 print(F.mro()) 30 31 # 输出 32 ''' 33 [<class '__main__.F'>, <class '__main__.D'>, <class '__main__.B'>, <class '__main__.E'>, <class '__main__.C'>, <class '__main__.A'>, <class '__main__.G'>, <class 'object'>] 34 '''