Showing posts with label Polymorphism in Python. Show all posts
Showing posts with label Polymorphism in Python. Show all posts

Thursday, July 10, 2025

🧠 Polymorphism in Python — One Name, Many Forms!

 Have you ever seen your teacher write with a pen, then with a marker, and then type on a keyboard?

All three are different, but the action is the same: writing ✍️

This is exactly what Polymorphism means in Python — one function or method can work in many different ways depending on the object!


🎭 What is Polymorphism?

Polymorphism is a fancy word that comes from Greek:

  • "Poly" means many

  • "Morph" means forms

So Polymorphism = many forms 🌀

In Python, polymorphism allows us to:

  • Use the same function name for different objects

  • Write less code and do more work


🧒 Real-Life Example: Animals Making Sounds

Let’s say we have different animals, and they all make sounds — but each makes a different sound.

class Dog:
def speak(self): print("Woof! 🐶") class Cat: def speak(self): print("Meow! 🐱") class Cow: def speak(self): print("Moo! 🐮")

Now let’s call their speak() method:

animals = [Dog(), Cat(), Cow()]
for animal in animals: animal.speak()

💬 Output:

Woof! 🐶
Meow! 🐱 Moo! 🐮

🎉 Even though the method name is the same (speak()), each animal does something different. That’s Polymorphism in action!


🔁 Polymorphism with Functions

You can also write a function that works with many object types:

def animal_sound(animal):
animal.speak()
d = Dog()
c = Cat() animal_sound(d) animal_sound(c)

✅ The same function behaves differently depending on what you pass into it!


🎮 Mini Challenge Time!

Create two classes:

  • Car → method move() → prints "Driving on the road 🚗"

  • Boat → method move() → prints "Sailing on water 🚤"

Then write a loop to call move() for both.

Can you do it? Try it out!


🧠 Why Polymorphism is Cool:

BenefitWhat it Means
✅ Less RepetitionNo need to write same function again
🔁 ReusabilityUse same function for different objects
📦 Clean CodeEasier to read and manage your program

🔮 Summary

TermWhat It Means
PolymorphismOne name, many behaviors
MethodA function inside a class
ClassA blueprint to create objects

🧠 Real-World Examples

  • print() works for text, numbers, and even lists!

print("Hello")
print(123) print([1, 2, 3])

That’s built-in polymorphism in Python!


🚀 Coming Next

  • ✨ Encapsulation — hide your data like a secret vault

  • 🧬 Inheritance — share features between parent and child classes


🎁 Bonus: Try This!

class Shape:
def area(self): print("I don't know the shape!") class Square(Shape): def area(self): print("Area = side × side") class Circle(Shape): def area(self): print("Area = π × r × r")
shapes = [Square(), Circle()]
for shape in shapes: shape.area()

🚀 Exploring Gemini AI and Python: A Beginner’s Guide for School Students

 Have you ever wondered how your favorite apps recognize your face, suggest videos, or even talk back like a real human? Welcome to the worl...