This article example describes the order of execution of Python multiple inheritance method resolution. Shared for your reference, as follows:
Any language that implements multiple inheritance has to deal with potential naming conflicts caused by unrelated ancestor classes implementing methods with the same name
class A: def say(self): print("A Hello:", self) class B(A): def eat(self): print("B Eating:", self) class C(A): def eat(self): print("C Eating:", self) class D(B, C): def say(self): super().say() print("D Hello:", self) def dinner(self): () super().say() () super().eat() (self)
Here both B and C implement the eat method.
If the () method is called on an instance of D, which eat method is run?
>>> d = D() >>> () B Eating: <__main__.D object at 0x7fb90c627f60> >>> (d) C Eating: <__main__.D object at 0x7fb90c627f60>
All methods in the superclass can be called directly, but you have to pass the instance as an explicit parameter.
Python can tell which method () is calling because it traverses the inheritance graph in a particular order. This order is called the Method Resolution Order (MRO). Classes have an attribute called __mro__, whose value is a tuple that lists the superclasses in method resolution order, from the current class up to the object class. The __mro__ attribute for class D looks like this:
>>> D.__mro__ (<class '__main__.D'>, <class '__main__.B'>, <class '__main__.C'>, <class 'object'>) >>> d = D() >>> () A Hello: <__main__.D object at 0x7fb90bd7eb70> D Hello: <__main__.D object at 0x7fb90bd7eb70> A Hello: <__main__.D object at 0x7fb90bd7eb70> B Eating: <__main__.D object at 0x7fb90bd7eb70> B Eating: <__main__.D object at 0x7fb90bd7eb70> C Eating: <__main__.D object at 0x7fb90bd7eb70>
first()
The run of class A of thesay()
Print out a second line of information about yourself
second reasonsuper().say()
The run of class A of thesay()
third()
Based on__mro__
The method found is the eat method implemented in class B.
fourthsuper().eat()
Based on__mro__
The method found is the eat method implemented in class B.
fifth(self)
Ignore mro and find the eat method implemented by the C class.
Readers interested in more Python related content can check out this site's topic: thePython Object-Oriented Programming Introductory and Advanced Tutorials》、《Python Data Structures and Algorithms Tutorial》、《Summary of Python function usage tips》、《Summary of Python string manipulation techniques》、《Summary of Python coding manipulation techniquesand thePython introductory and advanced classic tutorials》
I hope that the description of this article will be helpful for you Python Programming.