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
- B.method
- A.method
- B.method
In the second example, you get
- A.method
- B.method
- B.method
The first one doesn't work because it's inconsistent in regards to whether B.method comes before or after A.method.