In this lesson, you will learn how to build a class that inherits attributes and methods from two or more parent classes to merge distinct feature sets into one object.
Combining Functionality with Multiple Inheritance
So far, we have explored single inheritance, where a child class extends one parent. However, real-world objects often represent a blend of different roles. Python allows a single class to inherit from multiple parents, meaning the child class gains access to the methods and attributes of every class listed in its definition.
The Mechanics of Multiple Parents
When you define a class, you simply list all the desired parent classes inside the parentheses, separated by commas. Python will look for attributes or methods in these parents from left to right.
Imagine we are modeling a SmartPhone. It acts like a Camera (which captures photos) and a Phone (which makes calls).
class Camera:
def take_photo(self):
return "Click! Photo saved."
class Phone:
def make_call(self, number):
return f"Dialing {number}..."
# SmartPhone inherits from both
class SmartPhone(Camera, Phone):
def check_status(self):
return "SmartPhone is ready to use."
# Usage
my_device = SmartPhone()
print(my_device.take_photo()) # Inherited from Camera
print(my_device.make_call("555-0123")) # Inherited from Phone
print(my_device.check_status()) # Defined in SmartPhone
In this example, SmartPhone doesn't need to redefine how to take a photo or make a call; it automatically acquires those capabilities because it is a "child" of both Camera and Phone.
Why Use Multiple Inheritance?
This approach is powerful because it promotes code reuse by keeping specific behaviors in small, specialized classes. Instead of writing one massive "God class" that does everything, you create mix-and-match components. You can then assemble these components to create complex objects that possess all the behaviors required for their specific tasks.
As long as you keep your parent classes focused and distinct, multiple inheritance makes your code much more modular and easier to maintain.
Key Takeaway: Multiple inheritance allows a class to inherit features from several parents, enabling you to combine distinct behaviors into a single, cohesive object.