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())

Explanation:

  • We define a base class Shape with a method calculate_area().
  • We define two derived classes, Rectangle and Circle, that inherit from the Shape class and override the calculate_area() method with their specific implementations.
  • We create objects of both classes, rectangle and circle.
  • 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:

Task 14:

Create a class called Animal with a method make_sound() that prints a generic sound. Create two derived classes, Cat and 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.