Home > Article > Backend Development > Why Does the MRO in My New-Style Python Class Not Behave as Expected?
MRO (Method Resolution Order) in New-Style Classes
In Python, the Method Resolution Order (MRO) determines how methods are resolved in case of inheritance. In new-style classes, the MRO follows specific rules, as explained in the documentation of Python in a Nutshell (2nd Edition).
In the given example, the code uses new-style class syntax, but the MRO behaves as if it were an old-style class. The expected MRO for new-style classes should have placed Base3 before Base1 to correct this discrepancy.
The key difference between MRO in old-style and new-style classes lies in how they handle multiple inheritance when the same ancestor class appears multiple times. In old-style classes, the depth-first approach could lead to the incorrect resolution of methods. However, in new-style classes, the diamond inheritance pattern mentioned in the book is handled correctly.
For example, consider the following diamond inheritance hierarchy:
<code class="python">class A(object): x = 'a' class B(A): pass class C(A): x = 'c' class D(B, C): pass</code>
In old-style classes, the MRO would be D - B - A - C - A, leading to the value of x in D being 'a'. However, in new-style classes, the MRO is D - B - C - A - object, placing C before A and allowing the override of x in C to take effect. This resolves the diamond inheritance issue.
Therefore, the correct MRO for the given example is Derived - Base2 - Base1 - Base3 - object, but the current code produces an incorrect result due to the ambiguous MRO behavior. To rectify this, the class syntax should be updated to explicitly specify that the classes inherit from object to invoke the expected MRO semantics.
The above is the detailed content of Why Does the MRO in My New-Style Python Class Not Behave as Expected?. For more information, please follow other related articles on the PHP Chinese website!