Python FunctionsPython Functions1

Python Exception HandlingPython Exception Handling1

🔍

Python Polymorphism – Same Thing, Different Behavior



Let’s learn about a big-sounding word: Polymorphism. Don’t worry — it’s simpler than it sounds!

What is Polymorphism?

Polymorphism means “many forms.”

It’s a concept where something (like a function or method) behaves differently based on the object it is working with.

Imagine this: A person can be a student, a player, and a singer. Same person — but different roles. That’s the idea behind polymorphism.

Simple Example 1: len() Function

Python has a built-in function len() that gives you the length of something.

print(len("hello"))       # Length of a string
print(len([1, 2, 3, 4]))  # Length of a list
print(len((10, 20)))      # Length of a tuple

Output:

5
4
2

Why This Output?

The same function (len()) gives correct results for different types — that’s polymorphism!

Simple Example 2: Polymorphism with Classes

Let’s look at how polymorphism works with objects from different classes.

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

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

# Using polymorphism
animals = [Dog(), Cat()]
for animal in animals:
    print(animal.speak())

Output:

Woof!
Meow!

Why This Output?

This is polymorphism — speak() behaves differently for different objects.

Polymorphism in Daily Life

Here are some fun examples:

Why Learn Polymorphism?

Conclusion

Polymorphism allows the same action to work differently depending on the object. Python uses this to make code simple, clean, and powerful. You’ll see more of this when you learn about inheritance and advanced classes!



Welcome to ProgramGuru

Sign up to start your journey with us

Support ProgramGuru.org

You can support this website with a contribution of your choice.

When making a contribution, mention your name, and programguru.org in the message. Your name shall be displayed in the sponsors list.

PayPal

UPI

PhonePe QR

MALLIKARJUNA M