πΉ What is Polymorphism?
The word Polymorphism means:
Poly = many, morph = form
So, Polymorphism = many forms
π In Python, the same function or method can work in different ways depending on the object.
πΉ Why Use Polymorphism?
β
Makes code flexible
β
Easy to understand and update
β
Helps work with different objects in a similar way
πΉ Example: Polymorphism with Functions
def add(a, b):
return a + b
print(add(3, 4)) # Numbers
print(add("Hi ", "Tom")) # Strings
β
Same function name add()
works with numbers and strings β this is polymorphism.
πΉ Polymorphism with Classes
Letβs see two different classes using the same method name:
class Dog:
def speak(self):
print("Dog barks")
class Cat:
def speak(self):
print("Cat meows")
def animal_sound(animal):
animal.speak()
d = Dog()
c = Cat()
animal_sound(d)
animal_sound(c)
β
Different objects (Dog
, Cat
) use the same method speak()
in different ways.
πΉ Polymorphism with Inheritance
class Vehicle:
def move(self):
print("Vehicle is moving")
class Car(Vehicle):
def move(self):
print("Car is driving")
class Boat(Vehicle):
def move(self):
print("Boat is sailing")
def start_trip(vehicle):
vehicle.move()
v1 = Car()
v2 = Boat()
start_trip(v1)
start_trip(v2)
β
move()
method works differently for each object. This is runtime polymorphism.
πΉ Built-in Polymorphism Example
print(len("Python")) # Output: 6
print(len([1, 2, 3, 4])) # Output: 4
print(len((10, 20, 30))) # Output: 3
β
len()
function works with string, list, tuple β same function name, many forms.
π Practice Questions with Answers
β Q1: Create a method called greet()
in two classes: English
and Spanish
.
β Answer:
class English:
def greet(self):
print("Hello")
class Spanish:
def greet(self):
print("Hola")
def say_hello(obj):
obj.greet()
e = English()
s = Spanish()
say_hello(e)
say_hello(s)
β Q2: Write a function that accepts any shape class and prints area using area()
method.
β Answer:
class Circle:
def area(self):
print("Area of Circle: ΟrΒ²")
class Square:
def area(self):
print("Area of Square: sideΒ²")
def print_area(shape):
shape.area()
c = Circle()
s = Square()
print_area(c)
print_area(s)
π§Ύ Summary Table
Term | Meaning |
---|---|
Polymorphism | One method or function, many forms |
Built-in | Functions like len() , + , etc. |
User-defined | Methods in different classes with same name |
π― Quick Recap
- Polymorphism helps the same method name work in different ways.
- It can be seen in:
- Functions
- Classes
- Inheritance
- Built-in functions
Leave a Reply