class First(object):
def __init__(self):
print("first")
class Second(First):
def __init__(self):
print("second")
class Third(First, Second):
def __init__(self):
print("third")
Source
Why can't Python create a consistent MRO? It seems to me it's pretty clear:
But if you try it out:
TypeError: Error when calling the metaclass bases
Cannot create a consistent method resolution
order (MRO) for bases First, Second
The Method Resolution Order (MRO) is the set of rules that construct the linearization. In the Python literature, the idiom "the MRO of C" is also used as a synonymous for the linearization of the class C.
Method Resolution Order(MRO) it denotes the way a programming language resolves a method or attribute. Python supports classes inheriting from other classes. The class being inherited is called the Parent or Superclass, while the class that inherits is called the Child or Subclass.
To get the MRO of a class, you can use either the __mro__ attribute or the mro() method. The __mro__ attribute returns a tuple, but the mro() method returns a python list.
To be "consistent" the MRO should satisfy these constraints:
Your proposed hierarchy does not have any possible ordering meeting these constraints. Because Third is defined to inherit from First before Second, First should come before Second in the MRO. But because Second inherits from First, Second should come before First in the MRO. This contradiction cannot be reconciled.
You can read more about the precise method Python uses to compute the MRO, which is called the C3 linearization algorithm.
Python internally thinks not to have super class before sub-class.
According to your code. After Scanning or loading the classes, Python thinks the method resolution has to be:
Third -> Second -> First
Here, First is the super class of Second.
But while executing, after checking Third it confronts First which is the super class of Second.
Hence the TypeError.
class Third(First, Second): # Wrong
class Third(Second, First): # Correct
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With