Curriculum
Multiple inheritance is a feature in object-oriented programming languages like Python that allows a class to inherit attributes and methods from multiple parent classes. This means that a subclass can have multiple base classes, and it can access attributes and methods from all of them.
Here’s an example of how multiple inheritance works in Python:
class Animal: def __init__(self, name): self.name = name def move(self): print(f"{self.name} is moving.") class Mammal(Animal): def __init__(self, name): super().__init__(name) def feed_milk(self): print(f"{self.name} is feeding milk.") class Bird(Animal): def __init__(self, name): super().__init__(name) def lay_eggs(self): print(f"{self.name} is laying eggs.") class Platypus(Mammal, Bird): def __init__(self, name): super().__init__(name) perry = Platypus("Perry") perry.feed_milk() # Output: "Perry is feeding milk." perry.lay_eggs() # Output: "Perry is laying eggs." perry.move() # Output: "Perry is moving."
In this example, there are three classes: Animal
, Mammal
, and Bird
. The Mammal
and Bird
classes both inherit from the Animal
class. The Platypus
class inherits from both the Mammal
and Bird
classes. This means that the Platypus
class has access to all the attributes and methods of the Animal
, Mammal
, and Bird
classes.
When the feed_milk()
method is called on the perry
object, it is calling the method defined in the Mammal
class. When the lay_eggs()
method is called, it is calling the method defined in the Bird
class. Finally, when the move()
method is called, it is calling the method defined in the Animal
class.
Multiple inheritance can be a powerful tool for creating complex class hierarchies in Python, but it can also be difficult to manage and can lead to method name clashes or ambiguity. It is important to use it carefully and only when it makes sense for your particular use case.