Polymorphism is an essential concept in object-oriented programming (OOP) that allows methods or functions to operate on objects of different classes as long as they follow a certain interface or structure. In Python, polymorphism enables the same function or method to be used for objects of different types, making the code more flexible and extensible.
Benefits of Polymorphism
Flexibility and Extensibility: Functions and methods can work with different types, making it easier to extend code without changing existing logic.
Reusability: Generic code can handle multiple types, reducing redundancy.
Readability: Polymorphic functions make the code more readable and concise.
Types of Polymorphism
Duck Typing:
In Python, if an object behaves like a certain type (has the required methods or attributes), it can be used as that type, regardless of its actual class. This concept is known as “duck typing.”
For example, if an object has a fly()
method, it can be treated as a “flying” object, even if it’s not explicitly a subclass of a “FlyingObject” class.
class Bird:
def fly(self):
print("Bird is flying")
class Airplane:
def fly(self):
print("Airplane is flying")
def make_it_fly(flying_object):
# Duck typing - works if the object has a fly() method
flying_object.fly()
# Usage
bird = Bird()
airplane = Airplane()
make_it_fly(bird) # Outputs: Bird is flying
make_it_fly(airplane) # Outputs: Airplane is flying
Method Overriding
class Animal:
def sound(self):
print("Some generic animal sound")
class Dog(Animal):
def sound(self):
print("Woof woof")
class Cat(Animal):
def sound(self):
print("Meow")
# Usage
animals = [Dog(), Cat(), Animal()]
for animal in animals:
animal.sound() # Different sound based on the actual object type
Here, each subclass (Dog
, Cat
) provides its own version of the sound
method, overriding the one defined in the Animal
base class.
Operator Overloading
class Vector:
def __init__(self, x, y):
self.x = x
self.y = y
def __add__(self, other):
# Overloading the + operator to add two vectors
return Vector(self.x + other.x, self.y + other.y)
def __str__(self):
return f"Vector({self.x}, {self.y})"
# Usage
v1 = Vector(2, 3)
v2 = Vector(4, 5)
result = v1 + v2
print(result) # Outputs: Vector(6, 8)
The +
operator is overloaded in the Vector
class, allowing the addition of two Vector
objects.