CBen
CBen

Reputation: 13

Python: Class inherit

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

Answers (1)

Abdullah Ahmed Ghaznavi
Abdullah Ahmed Ghaznavi

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:

  1. each ancestor class appears exactly once
  2. a class always appears before its ancestor ("monotonicity")
  3. direct parents of the same class should appear in the same order as they are listed in class definition ("consistent local precedence order")
  4. if children of class A always appear before children of class B, then A should appear before B ("consistent extended precedence order")

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

Related Questions