0
0
Pythonprogramming~5 mins

Multiple inheritance syntax in Python

Choose your learning style9 modes available
Introduction

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

When you want a new class to have behaviors from two or more existing classes.
When you want to reuse code from multiple sources without rewriting it.
When modeling real-world things that naturally belong to multiple categories.
When you want to mix different functionalities like logging and data processing in one class.
Syntax
Python
class ChildClass(ParentClass1, ParentClass2):
    # class body

List all parent classes inside parentheses, separated by commas.

Python looks for methods in the order parents are listed (left to right).

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 a Book class that can both write and read by inheriting from Writer and Reader.

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

class Reader:
    def read(self):
        print("Reading...")

class Book(Writer, Reader):
    pass

b = Book()
b.write()
b.read()
OutputSuccess
Important Notes

If two parent classes have methods with the same name, Python uses the method from the first parent listed.

Use multiple inheritance carefully to avoid confusion and keep code clear.

Summary

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

List parent classes separated by commas inside parentheses after the class name.

Method resolution order follows the order of parents listed.