Python Polymorphism

Polymorphism in object-oriented programming allows objects of different classes to be treated as objects of a common type. This means you can write functions that work with objects of various types without needing to know their specific type at compile time.

Example 1: Method Overriding (a form of polymorphism)


    class Animal:
      def speak(self):
        print("Generic animal sound")
    
    class Dog(Animal):
      def speak(self):
        print("Woof!")
    
    class Cat(Animal):
      def speak(self):
        print("Meow!")
    
    
    animals = [Dog("Buddy"), Cat("Whiskers")]
    for animal in animals:
      animal.speak()  # Output: Woof! and Meow!
        

Here, both Dog and Cat have a speak method. The `animal.speak()` call dynamically invokes the correct version of the method based on the object's type at runtime.

Example 2: Using Polymorphism with a Function


    def animal_sound(animal):
      animal.speak()
    
    animal_sound(Dog("Rover"))  # Output: Woof!
    animal_sound(Cat("Mittens"))  # Output: Meow!
        

The `animal_sound` function can accept any `Animal`-type object without knowing its specific class.

Example 3: Polymorphism with Different Shapes (Illustrative)


    class Shape:
      def area(self):
        pass
    
    class Circle(Shape):
      def __init__(self, radius):
        self.radius = radius
    
      def area(self):
        return 3.14159 * self.radius * self.radius
    
    class Rectangle(Shape):
      def __init__(self, width, height):
        self.width = width
        self.height = height
    
      def area(self):
        return self.width * self.height
    
    shapes = [Circle(5), Rectangle(4, 6)]
    for shape in shapes:
      print(shape.area()) # Output: areas of each shape
        

This example illustrates polymorphism with a `Shape` base class and derived classes `Circle` and `Rectangle`. The `area()` method is defined differently in each, yet the same function call (`shape.area()`) works for different shape types.

Important Considerations

  • Abstraction: Polymorphism relies on defining common interfaces (like the `speak()` method in the examples). This allows you to work with objects without needing to know their exact class details.
  • Flexibility: Polymorphism makes code more adaptable because it can handle new object types without modifications to existing functions that rely on the common interface.