新式类多重继承原则:广度优先,从左到右
==================正确==================
In [19]: class P1(object):
...: def foo(self):
...: print('called P1-foo()')
...: class P2(object):
...: def foo(self):
...: print('called P2-foo()')
...: def bar(self):
...: print('called P2-bar()')
...: class C1(P1,P2): ###P1和P2顺序一致
...: pass
...: class C2(P1,P2): ###P1和P2顺序一致
...: def bar(self):
...: print('called C2-bar()')
...: class GC(C2,C1):
...: pass
In [20]: gc.foo()
called P1-foo() ### GC--->C2--->C1--->P2
In [21]: gc.bar()
called C2-bar() ### GC--->C2--->C1
==================正确==================
In [31]: class P1(object):
...: def foo(self):
...: print('called P1-foo()')
...: class P2(object):
...: def foo(self):
...: print('called P2-foo()')
...: def bar(self):
...: print('called P2-bar()')
...: class C1(P2,P1): ###P2和P1顺序一致
...: pass
...: class C2(P2,P1): ###P2和P1顺序一致
...: def bar(self):
...: print('called C2-bar()')
...: class GC(C2,C1):
...: pass
In [33]: gc.foo()
called P2-foo() ### GC--->C2--->C1--->P2
In [34]: gc.bar()
called C2-bar() ### GC--->C2--->C1
==================正确==================
In [29]: class P1(object):
...: def foo(self):
...: print('called P1-foo()')
...: class P2(object):
...: def foo(self):
...: print('called P2-foo()')
...: def bar(self):
...: print('called P2-bar()')
...: class C1(P2,P1):
...: pass
...: class C2(P1,P2):
...: def bar(self):
...: print('called C2-bar()')
...:
==================错误==================
In [26]: class P1(object):
...: def foo(self):
...: print('called P1-foo()')
...: class P2(object):
...: def foo(self):
...: print('called P2-foo()')
...: def bar(self):
...: print('called P2-bar()')
...: class C1(P2,P1): ###P2和P1
...: pass
...: class C2(P1,P2): ###P1和P2
...: def bar(self):
...: print('called C2-bar()')
...: class GC(C2,C1):
...: pass
...:
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-26-7eeba137b395> in <module>()
12 def bar(self):
13 print('called C2-bar()')
---> 14 class GC(C2,C1):
15 pass
TypeError: Cannot create a consistent method resolution
order (MRO) for bases P2, P1
原因分析:
子类GC在继承C2和C1时,无法分辨C1和C2中P1和P2的继承关系,一会(P1,P2)一会又是(P2,P1),导致GC继承MRO出错。
因为继承顺序发生了改变,所以gc.foo()和gc.bar()调用的结果也发生了改变。
TypeError: Cannot create a consistent method resolution order (MRO) for bases P1, P2
最新推荐文章于 2025-01-11 23:58:13 发布