Python : Polymorphism

Polymorphism is a fundamental concept in object-oriented programming (OOP) that allows objects of different classes to be treated as objects of a common superclass. It enables you to use a single interface to manipulate objects of various types, providing flexibility and extensibility in your code. Polymorphism in Python is achieved through method overriding and duck typing. Here's an overview of polymorphism in Python:

Method Overriding:


Method overriding allows subclasses to provide a specific implementation of a method that is already defined in its superclass. When a method is called on an object, Python looks for the method in the object's class and its superclass hierarchy, starting from the most specific subclass.


class Animal:
    def sound(self):
        print("Animal makes a sound")

class Dog(Animal):
    def sound(self):
        print("Dog barks")

class Cat(Animal):
    def sound(self):
        print("Cat meows")

def make_sound(animal):
    animal.sound()

dog = Dog()
cat = Cat()

make_sound(dog)  # Output: Dog barks
make_sound(cat)  # Output: Cat meows

 

Duck Typing:


Duck typing is a concept in Python that focuses on the object's behavior rather than its type. If an object behaves like a certain type (i.e., it supports the required methods and operations), it can be treated as that type, regardless of its actual class or type.


class Dog:
    def sound(self):
        print("Dog barks")

class Cat:
    def sound(self):
        print("Cat meows")

def make_sound(animal):
    animal.sound()

dog = Dog()
cat = Cat()

make_sound(dog)  # Output: Dog barks
make_sound(cat)  # Output: Cat meows

Operator Overloading:


Operator overloading allows objects to define their own behavior for certain operators (e.g., +, ,*) by implementing special methods such as __add__(), __sub__(), __mul__(), etc. This enables polymorphic behavior for operators across different classes.


class Vector:
    def __init__(self, x, y):
        self.x = x
        self.y = y

    def __add__(self, other):
        return Vector(self.x + other.x, self.y + other.y)

v1 = Vector(1, 2)
v2 = Vector(3, 4)
v3 = v1 + v2
print(f"({v3.x}, {v3.y})")  # Output: (4, 6)

 

Benefits of Polymorphism:

 

  • Code reusability: Polymorphism allows you to write generic code that can operate on objects of different types.
  • Flexibility: You can extend the functionality of existing classes without modifying their implementation.
  • Extensibility: New subclasses can be added without affecting existing code.

Polymorphism is a powerful concept in Python that promotes code reuse, flexibility, and extensibility, making it easier to write clean, modular, and maintainable code. It allows you to write more generic and flexible code that can adapt to changes and new requirements in your software.