Multiple Inheritance in Python: What It Is and How It Works
multiple inheritance means a class can inherit features from more than one parent class. This allows a new class to combine behaviors and properties from multiple sources, making code reuse flexible and powerful.How It Works
Multiple inheritance in Python lets a class get methods and properties from more than one parent class. Imagine you have two different toolkits, each with unique tools. By inheriting from both, your new class gets all the tools from both toolkits.
Python uses a method resolution order (MRO) to decide which parent’s method to use if there are conflicts. It checks parents in a specific order to find the right method to run. This way, Python keeps things organized even when multiple parents have methods with the same name.
Example
This example shows a class SmartPhone inheriting from two classes: Camera and Phone. It can use methods from both parents.
class Camera: def take_photo(self): return "Photo taken" class Phone: def make_call(self): return "Calling..." class SmartPhone(Camera, Phone): pass phone = SmartPhone() print(phone.take_photo()) print(phone.make_call())
When to Use
Use multiple inheritance when you want a class to combine features from different classes without rewriting code. For example, a SmartDevice might inherit from both InternetEnabled and BatteryPowered classes to get internet and battery features.
It is helpful in real-world projects where objects naturally share multiple roles or capabilities, like a flying car inheriting from both Car and Airplane classes.
Key Points
- Multiple inheritance allows a class to inherit from more than one parent class.
- Python uses method resolution order (MRO) to handle method conflicts.
- It helps combine different behaviors in one class without duplicating code.
- Use it carefully to avoid complex and confusing class hierarchies.