In Python, you can achieve multiple inheritance by inheriting from two or more classes. Multiple inheritance allows a class to inherit attributes and methods from multiple parent classes. Here’s an example of how to inherit one class from two classes:
class ParentClass1: def method1(self): print("Method from ParentClass1") class ParentClass2: def method2(self): print("Method from ParentClass2") class ChildClass(ParentClass1, ParentClass2): def method3(self): print("Method from ChildClass") # Create an instance of ChildClass child_instance = ChildClass() # Access methods from both parent classes child_instance.method1() child_instance.method2() # Access method from the child class child_instance.method3() In this example,
ChildClassis inheriting from both
ParentClass2. As a result, an instance of
ChildClasshas access to methods from both parent classes as well as its own methods.
Keep in mind the following points when using multiple inheritance:
- Method Resolution Order (MRO): Python uses the C3 Linearization algorithm to determine the order in which methods are looked up in the inheritance hierarchy.
- Diamond Problem: In some cases, multiple inheritance can lead to ambiguity, especially when a class inherits from two classes that have a common base class. This is known as the “diamond problem.” Python resolves this using the MRO.
- Super() Function: When calling methods in a multiple inheritance scenario, it’s a good practice to use the
super()function to ensure proper method chaining and avoid ambiguity.
- Design Considerations: Multiple inheritance can make code more complex. It’s important to design your classes carefully to avoid confusion and maintainability issues.
- Composition: In some cases, composition (creating objects of other classes within your class) might be a more suitable alternative to multiple inheritance.
Remember that while multiple inheritance can be powerful, it requires careful consideration of class interactions, method resolution order, and code organization.