Python
super()
multiple inheritance
object-oriented programming
programming教程

How does Python's super work with multiple inheritance?

Master System Design with Codemia

Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.

In object-oriented programming, multiple inheritance introduces complexity as it allows a class to inherit from more than one parent class. Python's super() function is a powerful tool that helps manage this complexity by providing a way to access inherited methods that can be beneficial for method resolution in classes employing multiple inheritance. Understanding how super() operates in multiple inheritance scenarios requires familiarity with the Method Resolution Order (MRO), which is central to Python's handling of method lookups.

Understanding Python's super() in Multiple Inheritance

Method Resolution Order (MRO)

The method resolution order is the order in which Python looks for a method or attribute in a hierarchy of classes. Python uses the C3 linearization algorithm (also known as C3 superclass linearization) to determine the MRO.

The MRO can be obtained using the __mro__ attribute or the mro() method of a class.

Here is an example that demonstrates how Python computes the MRO:

python
1class A:
2    def show(self):
3        print("A")
4
5class B(A):
6    def show(self):
7        print("B")
8
9class C(A):
10    def show(self):
11        print("C")
12
13class D(B, C):
14    def show(self):
15        print("D")
16
17print(D.__mro__)

In this example, D inherits from both B and C, both of which inherit from A. When calling D.__mro__, Python returns the method resolution order as follows:

 
(<class '__main__.D'>, <class '__main__.B'>, <class '__main__.C'>, <class '__main__.A'>, <class 'object'>)

Utilizing super()

The super() function enables calling a method in a superclass from a subclass's method. In a single inheritance scenario, super() is straightforward, but in multiple inheritance, it adheres to the MRO. This ensures that when super() is called, it respects the order defined by MRO to determine which method to call next.

Consider the same classes with super():

python
1class A:
2    def show(self):
3        print("A")
4
5class B(A):
6    def show(self):
7        print("B")
8        super().show()
9
10class C(A):
11    def show(self):
12        print("C")
13        super().show()
14
15class D(B, C):
16    def show(self):
17        print("D")
18        super().show()
19
20d = D()
21d.show()

When d.show() is called, the following output demonstrates how super() employs the MRO:

 
1D
2B
3C
4A

super() starts from the current method (in D) and proceeds according to the MRO.

Advantages of Using super() in Multiple Inheritance

  • Maintainability: Using super() enhances maintainability by eliminating hard-coded calls to specific parent classes, ensuring that any change in the MRO automatically reflects in method calls.
  • Dynamic Hierarchy: It supports dynamically changed hierarchy without needing to rewrite method calls based on new parent class structures.
  • Avoiding Redundancy: super() prevents redundant code segments by allowing shared methods in parent classes to be called once.

Key Considerations

When using super() in multiple inheritance, it's crucial to design the base classes with super() in mind, ensuring they cooperate correctly. This involves:

  • Cooperative Methods: All methods in the hierarchy must be designed to tolerate and appropriately handle delegation to super().
  • Consistent Signatures: Methods intended to be part of the cooperative inheritance pattern should have a consistent signature.

Here's a table that summarizes key points of super() in the context of multiple inheritance:

AspectExplanation
MRODetermines the order to search classes for methods.
super()Calls the next method in the MRO.
FlexibilityReduces rigidity by allowing easy hierarchy changes.
Code RedundancyAvoids coding the same logic multiple times in the same class hierarchy.
Method CompatibilityRequires compatibility with super() in all relevant methods.
TroubleshootingDebugging MRO issues might require understanding C3 linearization deeply.

Conclusion

In summary, Python's super() function is a crucial tool for managing method calls in a multiple inheritance scenario. It simplifies and clarifies the complex interactions inherent in class hierarchies. By understanding its mechanics through MRO and ensuring methods cooperate effectively, developers can build maintainable and robust object-oriented systems.


Course illustration
Course illustration

All Rights Reserved.