Super() in Python Multiple Inheritance
Multiple inheritance in Python brings forth the question of how super() interacts with it. Consider the following code:
class First(object): def __init__(self): print("first") class Second(object): def __init__(self): print("second") class Third(First, Second): def __init__(self): super(Third, self).__init__() print("that's it")
Now, which parent method of Third does super().__init__ refer to? Can you choose which one runs?
To understand super() in this context, we delve into the concept of Method Resolution Order (MRO). In Python, the MRO defines the order in which methods are resolved when multiple inheritance is involved.
In our example, Third() will call First.__init__. Python examines each attribute in the class's parents from left to right. For __init__, Python looks in First first, and if it's not found there, it checks in Second.
The situation grows more complex with intertwined inheritance. Read more about this in Guido's blog post on MRO. However, Python will generally maintain the order of inheritance as written, starting with the child class itself.
Consider the following example:
class First(object): def __init__(self): print("first") class Second(First): def __init__(self): print("second") class Third(First): def __init__(self): print("third") class Fourth(Second, Third): def __init__(self): super(Fourth, self).__init__() print("that's it")
Here, the MRO would be [Fourth, Second, Third, First].
It's important to note that if Python cannot determine a coherent MRO, it raises an exception rather than resorting to potentially unexpected behavior.
Additionally, it's worth mentioning that the examples provided do not use super() calls. Their purpose is to demonstrate how the MRO is constructed, not to print specific output. You are encouraged to experiment with super() calls to gain a deeper understanding of Python's inheritance model.
The above is the detailed content of How Does `super()` Resolve Method Calls in Python Multiple Inheritance?. For more information, please follow other related articles on the PHP Chinese website!