Polymorphism is an essential concept in object-oriented programming (OOP) that allows objects of different classes to be treated as objects of a common superclass. It promotes code flexibility and reusability.
In Python, polymorphism is achieved through method overriding, operator overloading, and built-in functions that work with different types of objects.
What is Polymorphism?
The word Polymorphism is derived from the Greek words “poly” (meaning many) and “morph” (meaning forms). It allows a single method or operator to behave differently based on the object it is acting upon.
Types of Polymorphism
- Method Overriding: Redefining a method in a child class that already exists in the parent class.
- Operator Overloading: Defining custom behavior for standard operators.
1. Method Overriding
Method overriding occurs when a child class provides a specific implementation of a method already defined in its parent class.
Example:
class Animal: def sound(self): return "Animal makes a sound" class Dog(Animal): def sound(self): # Method overriding return "Dog barks" class Cat(Animal): def sound(self): # Method overriding return "Cat meows" # Using polymorphism animals = [Dog(), Cat()] for animal in animals: print(animal.sound()) # Output: # Dog barks # Cat meows
2. Operator Overloading
Operator overloading allows you to redefine the behavior of operators for custom objects.
Example:
class Point: def __init__(self, x, y): self.x = x self.y = y def __add__(self, other): return Point(self.x + other.x, self.y + other.y) def __str__(self): return f"({self.x}, {self.y})" p1 = Point(2, 3) p2 = Point(4, 5) p3 = p1 + p2 # Operator overloading for '+' print(p3) # Output: (6, 8)
Polymorphism with Built-in Functions
Many built-in Python functions, like len()
, exhibit polymorphism by working with different types of objects.
Example:
print(len("Hello")) # Output: 5 (string length) print(len([1, 2, 3, 4])) # Output: 4 (list length)
Real-world Example of Polymorphism
Polymorphism is widely used in real-world applications to create flexible and reusable code.
Example – Payment System:
class Payment: def pay(self): pass class CreditCardPayment(Payment): def pay(self): return "Payment made with Credit Card" class PayPalPayment(Payment): def pay(self): return "Payment made with PayPal" def process_payment(payment): print(payment.pay()) # Using polymorphism credit = CreditCardPayment() paypal = PayPalPayment() process_payment(credit) # Output: Payment made with Credit Card process_payment(paypal) # Output: Payment made with PayPal
Conclusion
Polymorphism is a key feature of Python that enhances code reusability and flexibility. By understanding and applying method overriding, operator overloading, and polymorphic behavior in built-in functions, you can write cleaner and more maintainable code.