? Polymorphism
? Polymorphism
In simple terms, polymorphism allows the same function, operator, or method to behave
differently depending on the object or context it's being used with.
🔸 Real-life Analogy
They all have a method called drive(), but they behave differently. That’s polymorphism.
📜 Program:
class Dog:
def speak(self):
return "Woof!"
class Cat:
def speak(self):
return "Meow!"
# Function that works with any object that has a 'speak' method
def animal_sound(animal):
print(animal.speak())
# Main Program
dog = Dog()
cat = Cat()
animal_sound(dog)
animal_sound(cat)
💡 Output:
Woof!
Meow!
📝 Explanation:
def animal_sound(animal):
print(animal.speak())
class Dog:
def speak(self):
return "Woof!"
class Cat:
def speak(self):
return "Meow!"
✅ Output
Woof!
Meow!
Because:
✅ Summary
🔶 2. Operator Overloading
📜 Program:
class Book:
def __init__(self, pages):
self.pages = pages
def __str__(self):
return f"Total Pages: {self.pages}"
# Main Program
b1 = Book(100)
b2 = Book(150)
b3 = b1 + b2 # Calls __add__ method
print(b3) # Calls __str__ method
💡 Output:
📝 Explanation:
Python’s object-oriented system uses a well-defined set of special methods to define behavior
for common operators.
✅ Example in Context
class Book:
def __init__(self, pages):
self.pages = pages
python
CopyEdit
b1 = Book(100)
b2 = Book(150)
b3 = b1 + b2
Python runs:
python
CopyEdit
b3 = b1.__add__(b2)
✅ Summary
📜 Program:
class Animal:
def make_sound(self):
print("Some generic sound")
class Dog(Animal):
def make_sound(self):
print("Bark")
class Cat(Animal):
def make_sound(self):
print("Meow")
# Main Program
animals = [Dog(), Cat(), Animal()]
for a in animals:
a.make_sound()
💡 Output:
Bark
Meow
Some generic sound
📝 Explanation:
📜 Program:
class Shape:
def area(self):
# Abstract-like method (not enforced)
pass
class Rectangle(Shape):
def __init__(self, width, height):
self.width = width
self.height = height
def area(self):
return self.width * self.height
class Circle(Shape):
def __init__(self, radius):
self.radius = radius
def area(self):
return 3.14 * self.radius * self.radius
# Main Program
shapes = [Rectangle(10, 5), Circle(7)]
for shape in shapes:
print("Area:", shape.area())
💡 Output:
Area: 50
Area: 153.86
📝 Explanation:
The method area() is defined in base class and overridden in derived classes.
Using the same method name for different shape types demonstrates polymorphism.
🔚 Summary Table
Type Definition Python Example
Behavior depends on method name, not object
Duck Typing animal_sound(dog)
type
Redefining how operators work for user-defined __add__ in Book
Operator Overloading
objects class
Method Overriding Derived class modifies parent class method make_sound() in Dog
Interface-Based Shared method names with different
area() in Shape c
Polymorphism implementations across unrelated classes