Clarifying MRO in New-Style Classes
Unlike old-style classes, new-style classes introspect their base classes to establish a Method Resolution Order (MRO). This order determines the sequence in which methods are searched when a method is called on an object.
Resolving Inheritance Conflicts with MRO
The key distinction between MRO in new-style and old-style classes arises when the same ancestor class appears multiple times in the inheritance hierarchy. For instance, consider the following diamond inheritance case:
class Base1(object):
def amethod(self):
print("Base1")
class Base2(Base1):
pass
class Base3(object):
def amethod(self):
print("Base3")
class Derived(Base2, Base3):
pass
Legacy-Style MRO:
In legacy-style classes, the resolution order would be D - B - A - C - A. Here, when invoking D.amethod(), the definition in A is found first and overrides the definition in C.
New-Style MRO:
For new-style classes, the MRO is as follows:
D.__mro__
(<class '__main__.D'>, <class '__main__.B'>, <class '__main__.C'>,
<class '__main__.A'>, <type 'object'>)
Notice that A appears only once in this order, after all its subclasses. This ensures that overrides in subclasses, such as C's override of amethod, take precedence.
Understanding the Importance of MRO
The MRO in new-style classes resolves inheritance conflicts sensibly, allowing overrides to function correctly. It also avoids situations where multiple definitions of the same method appear in the resolution order, leading to ambiguous behavior. By understanding and utilizing MRO effectively, developers can design robust and maintainable inheritance hierarchies in Python.
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3