Reputation: 13
What is different between the two situation?
# Error: Cannot create a consistent method resolution order (MRO) for bases A, B
class A:
pass
class B(A):
pass
class C(A, B):
pass
# Current situation
class A:
pass
class B(A):
pass
class C(B, A):
pass
Upvotes: 1
Views: 105
Reputation: 2099
Your C
is inheriting from B
and A
. Because B
already inherits from A
Python now cannot determine what class to look methods up on first; either A
, or on B
, which would override things defined in A
.
You don't need to name all base classes of B
here; just inherit from that one class:
class C(B):
pass
B
already includes A
, you don't need to include it again.
Updated Area:
Note:
To explain you in more details:
Python needs to decide in which order to search through (direct and indirect) base classes when looking up an instance attribute / method. It does this by linearizing the inheritance graph, that is by converting the graph of base classes into a sequence, using an algorithm called C3 or MRO. The MRO algorithm is the unique algorithm that achieves several desirable properties:
With your code, the second constraint requires that B
appears first; the third constraint requires that A
appears first. Since there's no way to satisfy all constraints, python reports that your inheritance hierarchy is illegal.
This is not just a technical detail. In some (hopefully rare) cases, you might want to think about which class should be used to grab the method you called if the method is defined in multiple classes. The order in which you define base classes affects this choice.
Hope this helps you understand and helps you! :) Thankyou!
Upvotes: 2