Polymorphism in Python | One Name, Many Uses



πŸ”Ή 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

TermMeaning
PolymorphismOne method or function, many forms
Built-inFunctions like len(), +, etc.
User-definedMethods 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


Comments

Leave a Reply

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