Home > Enterprise >  Python MRO in plain English
Python MRO in plain English

Time:01-15

I'm new to Python and having troubles understanding Python MRO. Could somebody explain the question below as simple as possible?

Why this code throws TypeError: Cannot create a consistent method resolution:

class A:
  def method(self):
    print("A.method() called")
 
class B:
  def method(self):
    print("B.method() called")
 
class C(A, B):
  pass
 
class D(B, C):
  pass
 
d = D()
d.method()

While this code works fine:

class A:
  def method(self):
    print("A.method() called")
 
class B:
  def method(self):
    print("B.method() called")
 
class C(A, B):
  pass
 
class D(C, B):
  pass
 
d = D()
d.method()

CodePudding user response:

When you resolve the hierarchy of the methods in your first example, you get

  1. B.method
  2. A.method
  3. B.method

In the second example, you get

  1. A.method
  2. B.method
  3. B.method

The first one doesn't work because it's inconsistent in regards to whether B.method comes before or after A.method.

  • Related