πŸŒ€ Day 20: Polymorphism in Python — One Face, Many Roles

“Polymorphism is the art of doing different things... the same way.”

Think about a person.
At home, they’re a parent, at work a developer, at the gym a trainer, and in traffic a driver.

Same person, different roles — this is Polymorphism.

In Python and OOP, polymorphism allows you to write code that works across different types, as long as they follow the expected behavior.

                                         




🧠 What is Polymorphism?

Polymorphism means “many forms”.
In Python, it lets us use the same method name across different classes — and each class handles it in its own way.

This makes your code flexible, reusable, and elegant.


🎭 Real-life Analogy

Think of the + symbol:

  • 2 + 3 → Adds numbers

  • "Hello" + " World" → Joins strings

  • [1, 2] + [3, 4] → Combines lists

Same operator, multiple behaviors depending on context.
That’s operator polymorphism.

πŸ§ͺ Polymorphism with Functions and Classes

Let’s take two classes:

 


We can now use them in a single loop:

                                      

Output:
                            

Even though the objects are from different classes, they respond to the same method speak() in their own way.

🧬 Duck Typing in Python

Python is dynamically typed.
As long as an object has a method, we don’t care what type it is.

"If it walks like a duck and quacks like a duck... it's a duck."


 This is polymorphism by duck typing — we don’t check types, we just trust behavior.

πŸŒ€ Method Overriding (Runtime Polymorphism)

This happens when a child class overrides a method from the parent class.

                                        



Same method name fly(), different output based on the object.

πŸ” Why Polymorphism Matters?

  • Allows flexible and extensible code

  • Encourages DRY (Don't Repeat Yourself)

  • Makes your code adapt to future changes easily

✅ Key Takeaways

  • Polymorphism allows one method to behave differently across classes.

  • You’ve already seen it in action with +, *, and more.

  • Python uses duck typing — behavior > type.

  • Method Overriding enables runtime polymorphism in class hierarchies.


πŸš€ Quick Challenge

Create two classes: Rectangle and Circle
Each class should have a method area() that calculates its area differently.
Then call area() from a loop without checking class type.

Let’s see if you can think like Python! πŸ˜„


Keep This In Mind:

                               “Polymorphism is the art of doing different things... the same way.”






















Comments

Popular posts from this blog

Welcome to Python Fun Zone: Learn, Code, Build!

Day 1: Getting Started with Python – A Friendly Introduction for Beginners

Day 2: Variables and Data Types – The Building Blocks of Python 🐍