Python Multiple Inheritance
Multiple inheritance is a foundational concept in object-oriented programming (OOP) where a class can inherit methods and attributes from more than one parent class. Python supports this, allowing a subclass to combine functionality from multiple base classes.
This promotes flexibility and code reuse. However, it also raises the risk of method name conflicts. Python resolves such issues using its Method Resolution Order (MRO).
Syntax
class ParentA:
# Methods and attributes of ParentA
class ParentB:
# Methods and attributes of ParentB
class Child(ParentA, ParentB):
# Inherits from both ParentA and ParentB
Here:
ParentA,ParentB: Two distinct base classes.Child: The derived class that inherits from both.
Python determines which method to use using the order declared (left to right).
Example
In this example, the Duck class inherits from both Flyer and Swimmer, but due to Python’s MRO, the method from Flyer takes priority:
class Flyer:def ability(self):return "Can fly"class Swimmer:def ability(self):return "Can swim"class Duck(Flyer, Swimmer):passd = Duck()print(d.ability())
The output of this code is:
Can fly
Codebyte Example
In this codebyte example, the Tablet class inherits input methods from both Keyboard and Touchscreen, but the method from Keyboard is used due to its position in the inheritance list:
A visual overview of multiple inheritance:
+-------------+ +---------------+
| Keyboard | | Touchscreen |
|-------------| |---------------|
| input_method| | input_method |
+------+------+ +-------+-------+
\ /
\ /
▼ ▼
+--------------------+
| Tablet |
|--------------------|
| description() |
+--------------------+
All contributors
- Anonymous contributor
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.
Learn Python on Codecademy
- Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!
- Includes 6 Courses
- With Professional Certification
- Beginner Friendly.75 hours
- Learn the basics of Python 3.12, one of the most powerful, versatile, and in-demand programming languages today.
- With Certificate
- Beginner Friendly.24 hours