Python Polymorphism

🐍 Python Polymorphism

Polymorphism is an OOP concept that means “many forms”.
In Python, it allows objects of different classes to be treated in a similar way.


🔹 1️⃣ Types of Polymorphism in Python

  1. Duck Typing / Method Polymorphism (Same method name, different classes)

  2. Operator Overloading (Same operator behaves differently)

  3. Method Overriding (Child class method overrides parent method)


🔹 2️⃣ Duck Typing Example (Method Polymorphism)

class Dog:
def speak(self):
print("Woof! Woof!")

class Cat:
def speak(self):
print("Meow!")

def make_animal_speak(animal):
animal.speak() # works for any object with speak() method

d = Dog()
c = Cat()

make_animal_speak(d) # Woof! Woof!
make_animal_speak(c) # Meow!

Python is dynamically typed, so it doesn’t care about the object type.


🔹 3️⃣ Operator Overloading

Operators like +, -, * can behave differently depending on data types.

# Numbers
print(5 + 10) # 15

# Strings
print("Hello " + "World") # Hello World

# Custom Class
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)

p1 = Point(2, 3)
p2 = Point(4, 5)
p3 = p1 + p2
print(p3.x, p3.y) # 6 8

__add__ method allows overloading the + operator.


🔹 4️⃣ Method Overriding (Run-time Polymorphism)

Child class can override parent class method.

class Animal:
def speak(self):
print("Some generic sound")

class Dog(Animal):
def speak(self):
print("Woof! Woof!")

d = Dog()
d.speak() # Woof! Woof!

Can still call parent method using super():

class Dog(Animal):
def speak(self):
super().speak()
print("Woof! Woof!")

d = Dog()
d.speak()

Output:

Some generic sound
Woof! Woof!

🔹 5️⃣ Polymorphism With Built-in Functions

print(len("Python")) # 6 (string)
print(len([1,2,3,4])) # 4 (list)

Same function (len) works on different data types.


🔹 6️⃣ Summary Table

Type Example
Duck Typing / Method Polymorphism speak() in Dog & Cat
Operator Overloading + behaves differently for int, str, objects
Method Overriding Child class method overrides parent method
Built-in Function Polymorphism len() works on strings, lists, tuples

🔹 7️⃣ Real-World Example: Payment System

class CreditCard:
def pay(self):
print("Paid using Credit Card")

class UPI:
def pay(self):
print("Paid using UPI")

def process_payment(method):
method.pay()

cc = CreditCard()
upi = UPI()

process_payment(cc) # Paid using Credit Card
process_payment(upi) # Paid using UPI

Same function process_payment works for different payment methods — this is polymorphism.


Polymorphism makes code flexible, reusable, and clean.

CodeCapsule

Sanjit Sinha — Web Developer | PHP • Laravel • CodeIgniter • MySQL • Bootstrap Founder, CodeCapsule — Student projects & practical coding guides. Email: info@codecapsule.in • Website: CodeCapsule.in

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *