free geoip
59

Python Multiple Inheritance Examples

Python multiple inheritance allows a class to inherit attributes and methods from more than one parent class. It is one…

Python multiple inheritance allows a class to inherit attributes and methods from more than one parent class. It is one of the most powerful features of Python’s object-oriented programming (OOP) model. In this article, you’ll learn how multiple inheritance works, how to use it properly, and see several real-world examples with complete code to help you master the concept.

Python Multiple Inheritance Examples

What Is Multiple Inheritance in Python?

In Python, inheritance allows one class (child or subclass) to derive properties and methods from another class (parent or superclass). When a subclass inherits from more than one superclass, it’s called multiple inheritance.

For example:

class Parent1:
    def feature1(self):
        print("Feature 1 from Parent1")

class Parent2:
    def feature2(self):
        print("Feature 2 from Parent2")

class Child(Parent1, Parent2):
    def child_feature(self):
        print("Feature from Child")

obj = Child()
obj.feature1()
obj.feature2()
obj.child_feature()

In this example, the class Child inherits both feature1() from Parent1 and feature2() from Parent2. This is a simple demonstration of multiple inheritance.

How Python Resolves Method Order (MRO)

When a class inherits from multiple classes, Python determines the order in which to search for methods and attributes using something called the Method Resolution Order (MRO). You can view the MRO of any class using the __mro__ attribute or the mro() method.

print(Child.__mro__)
# Output: (<class '__main__.Child'>, <class '__main__.Parent1'>, <class '__main__.Parent2'>, <class 'object'>)

Python follows the C3 linearization algorithm to determine the MRO. It ensures a consistent and predictable order for method lookup, avoiding conflicts when multiple classes define the same method.

Example: Multiple Inheritance with Overridden Methods

Let’s see how Python handles method overriding when multiple parents define the same method name:

class A:
    def greet(self):
        print("Hello from A")

class B:
    def greet(self):
        print("Hello from B")

class C(A, B):
    pass

obj = C()
obj.greet()
print(C.__mro__)

Output:

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

Since class C inherits from A first, the greet() method from A is executed. This demonstrates that the MRO gives priority to the first base class listed in the class definition.

Practical Example: Employee and Manager

Now, let’s use a real-world scenario where multiple inheritance makes sense. Suppose we want to model an employee who is also a manager and a programmer. Each parent class will define its own set of attributes and methods.

class Employee:
    def __init__(self, name, salary):
        self.name = name
        self.salary = salary

    def show_details(self):
        print(f"Employee Name: {self.name}")
        print(f"Salary: {self.salary}")

class Manager:
    def manage_team(self):
        print("Managing the team and assigning tasks.")

class Programmer:
    def write_code(self):
        print("Writing efficient Python code.")

class TechLead(Employee, Manager, Programmer):
    def __init__(self, name, salary, project):
        super().__init__(name, salary)
        self.project = project

    def show_project(self):
        print(f"Current Project: {self.project}")

lead = TechLead("John Doe", 90000, "AI Assistant")
lead.show_details()
lead.manage_team()
lead.write_code()
lead.show_project()

Output:

Employee Name: John Doe
Salary: 90000
Managing the team and assigning tasks.
Writing efficient Python code.
Current Project: AI Assistant

In this example, TechLead inherits from Employee, Manager, and Programmer. The class can use all their methods, combining multiple functionalities in one place.

Example: Diamond Problem in Multiple Inheritance

The diamond problem occurs when a class inherits from multiple classes that share a common ancestor. Let’s see how Python resolves it:

class A:
    def greet(self):
        print("Hello from A")

class B(A):
    def greet(self):
        print("Hello from B")

class C(A):
    def greet(self):
        print("Hello from C")

class D(B, C):
    pass

obj = D()
obj.greet()
print(D.__mro__)

Output:

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

Python’s MRO ensures that the method from B is called before C, following the left-to-right inheritance order. The diamond problem is automatically managed by Python using C3 linearization, avoiding ambiguity.

When to Use Multiple Inheritance

Multiple inheritance can be very powerful, but it should be used carefully. You can use it when:

  • You want to combine distinct functionalities from multiple classes.
  • You are following a mixin design pattern (e.g., logging, authentication, etc.).
  • Your classes are small and modular, making inheritance predictable.

Mixin Example: Adding Logging Functionality

A common use case for multiple inheritance is mixins — lightweight classes that add additional functionality without changing the main class hierarchy.

class LoggerMixin:
    def log(self, message):
        print(f"[LOG]: {message}")

class Database:
    def save(self, data):
        print(f"Saving {data} to the database.")

class User(Database, LoggerMixin):
    def create_user(self, username):
        self.save(username)
        self.log(f"User {username} created successfully.")

user = User()
user.create_user("alice")

Output:

Saving alice to the database.
[LOG]: User alice created successfully.

This example shows a practical implementation of multiple inheritance to add reusable logging functionality without rewriting code.

Best Practices for Using Multiple Inheritance

  • Use multiple inheritance only when classes are logically independent.
  • Avoid naming conflicts between parent class methods.
  • Understand and check the MRO before relying on overridden methods.
  • Prefer composition over inheritance when possible.
  • Use mixins for reusable behaviors.

Conclusion

Python multiple inheritance is a powerful feature that enables developers to build flexible and reusable object-oriented designs. By combining functionalities from multiple classes, you can create more expressive and modular programs. However, always understand the method resolution order (MRO) and avoid unnecessary complexity to keep your code clean and maintainable.

With the examples above, you now have a clear understanding of how multiple inheritance works in Python, how to use mixins, and how to manage potential conflicts effectively.

rysasahrial

Leave a Reply

Your email address will not be published. Required fields are marked *