Welcome back to CodeYourCraft! Today, we're diving into one of Python's powerful features - Multiple Inheritance. This concept allows a class to inherit properties from multiple parent classes, providing a flexible and modular approach to object-oriented programming. Let's get started!
Multiple Inheritance is a mechanism in Python that permits a class to inherit attributes and methods from multiple parent classes. This is achieved by listing multiple parent classes in the class definition.
class ChildClass(ParentClass1, ParentClass2):
# class definitionMultiple Inheritance is useful when you need to reuse code from multiple classes. It helps to create more complex and flexible class hierarchies, reducing code duplication and promoting modularity.
Let's consider a simple example: a Vehicle class with common attributes like color and wheels, and two child classes, Car and Bike, each inheriting properties from the Vehicle class and adding their specific attributes.
class Vehicle:
def __init__(self, color, wheels):
self.color = color
self.wheels = wheels
class Car(Vehicle):
def __init__(self, color, wheels, engine):
super().__init__(color, wheels)
self.engine = engine
class Bike(Vehicle):
def __init__(self, color, wheels, gear):
super().__init__(color, wheels)
self.gear = gearIn this example, the Car and Bike classes inherit the color and wheels attributes from the Vehicle class, and each adds an extra attribute specific to their respective classes.
Python uses Method Resolution Order (MRO) to determine the order in which to search for methods when there are multiple inheritance. This order ensures that methods are found and executed correctly, even in complex class hierarchies.
Let's dive deeper with an advanced example. We'll create three classes: Animal, Mammal, and Pet. The Animal class has a common method make_sound(), the Mammal class adds a lives_birth() method, and the Pet class inherits both and adds a train() method.
class Animal:
def make_sound(self):
print("Generic animal sound")
def lives_birth(self):
print("Lives and gives birth")
class Mammal(Animal):
pass
class Pet(Mammal):
def train(self):
print("Training a pet")
# Example usage
dog = Pet()
dog.make_sound() # Output: Generic animal sound
dog.lives_birth() # Output: Lives and gives birth
dog.train() # Output: Training a petIn this example, we've created a simple class hierarchy, where Pet inherits from Mammal, which in turn inherits from Animal. This allows us to reuse code and create a more organized and modular codebase.
Which of the following classes inherits from `Mammal` and `Animal`?
That's it for today's lesson on Multiple Inheritance! In the next lesson, we'll explore another fascinating aspect of Python - Polymorphism. Until then, happy coding! 💡