Polymorphism is a fundamental concept in object-oriented programming that allows objects of different classes to be treated as objects of a common base class. It enables code flexibility and reusability by providing a consistent interface for interacting with different objects, regardless of their specific implementations.
Let’s explore polymorphism in Python:
# Polymorphism class Shape: def calculate_area(self): pass class Rectangle(Shape): def __init__(self, width, height): self.width = width self.height = height def calculate_area(self): return self.width * self.height class Circle(Shape): def __init__(self, radius): self.radius = radius def calculate_area(self): return 3.14 * self.radius ** 2 # Creating objects rectangle = Rectangle(5, 3) circle = Circle(7) # Calculating areas print("Rectangle area:", rectangle.calculate_area()) print("Circle area:", circle.calculate_area())
- We define a base class
Shapewith a method
- We define two derived classes,
Circle, that inherit from the
Shapeclass and override the
calculate_area()method with their specific implementations.
- We create objects of both classes,
- We call the
calculate_area()method on both objects, which invokes the appropriate method based on the object’s class.
Polymorphism allows us to treat the objects uniformly by using a common interface (
calculate_area() method in this example), even though they have different implementations.
Now it’s time for a practical task:
Create a class called
Animal with a method
make_sound() that prints a generic sound. Create two derived classes,
Dog, that inherit from
Animal. Override the
make_sound() method in each derived class to print the specific sound of a cat and a dog, respectively. Create objects of both derived classes and call the
make_sound() method on each object.
Once you’ve completed the task, you can proceed to the next lesson.