0
0
Pythonprogramming~5 mins

Why multiple inheritance exists in Python

Choose your learning style9 modes available
Introduction

Multiple inheritance lets a class use features from more than one parent class. This helps reuse code and combine different abilities in one place.

When you want a new class to have behaviors from two or more different classes.
When you want to combine features like 'can fly' and 'can swim' into one animal class.
When you want to reuse code from multiple existing classes without rewriting it.
When you want to organize code by separating different responsibilities into different classes.
When you want to create flexible and modular programs that mix and match features.
Syntax
Python
class ChildClass(ParentClass1, ParentClass2):
    pass

List all parent classes inside parentheses, separated by commas.

The child class inherits methods and properties from all listed parents.

Examples
Duck inherits from both Flyer and Swimmer, so it can fly and swim.
Python
class Flyer:
    def fly(self):
        print("I can fly!")

class Swimmer:
    def swim(self):
        print("I can swim!")

class Duck(Flyer, Swimmer):
    pass
Class C inherits from A and B. It uses A's greet method because A is listed first.
Python
class A:
    def greet(self):
        print("Hello from A")

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

class C(A, B):
    pass

c = C()
c.greet()
Sample Program

This program shows an Artist class that can both write and paint by inheriting from Writer and Painter.

Python
class Writer:
    def write(self):
        print("Writing words")

class Painter:
    def paint(self):
        print("Painting pictures")

class Artist(Writer, Painter):
    pass

art = Artist()
art.write()
art.paint()
OutputSuccess
Important Notes

Be careful with method names that appear in multiple parents; Python uses the order of inheritance to decide which one to use.

Multiple inheritance can make code harder to understand if overused, so use it wisely.

Summary

Multiple inheritance allows a class to get features from more than one parent.

It helps combine different abilities without rewriting code.

Python uses the order of parent classes to decide which method to use if there are duplicates.