Polymorphism

What is Polymorphism?

In simple words,

Polymorphism means → same action, different behavior

For Example:
If I want to ask "How are you?" to both my friend and client.
The way I ask will be different for both, right?

↳ For my friends, it would be like "Hey Girl, how are you doing?"
↳ For the client: "I hope this email finds you so well [Funny traditional way]🤣😁"

So, in every action, my way of asking is different, but the question, or I might say, the action is the same.

Or, I might say I am overriding the question functionality based on the person.

Same in code, Polymorphism lets you create one method name (like withdraw()), but it behaves differently for different classes.


Suppose You're Building a Banking App Again

You have different types of accounts:

  • SavingsAccount

  • CurrentAccount

  • DigitalWallet

And all of them have a method called withdraw().

But... rules for withdrawal are not same.


Now Let’s Code It:

class BankAccount:
    def withdraw(self, amount):
        pass

Child classes:

Here, child classes are overriding the withdraw method

Overriding → same method, redefined in child class

  • Happens in Inheritance

  • The parent class has a method

  • Child class gives its version of that method

class SavingsAccount(BankAccount):
    def withdraw(self, amount):
        print(f"SavingsAccount: Withdrew {amount} with balance check")

class CurrentAccount(BankAccount):
    def withdraw(self, amount):
        print(f"CurrentAccount: Withdrew {amount} with overdraft facility")

class DigitalWallet(BankAccount):
    def withdraw(self, amount):
        print(f"DigitalWallet: Used {amount} instantly")

Now you do this:

def make_withdrawal(account, amount):
    account.withdraw(amount)

Test it:

acc1 = SavingsAccount()
acc2 = CurrentAccount()
acc3 = DigitalWallet()

make_withdrawal(acc1, 100)  # SavingsAccount: Withdrew 100 with balance check
make_withdrawal(acc2, 200)  # CurrentAccount: Withdrew 200 with overdraft facility
make_withdrawal(acc3, 300)  # DigitalWallet: Used 300 instantly

So What Happened?

  • You used same function → make_withdrawal(account, amount)

  • But the result changed depending on which object you passed.

  • This is runtime polymorphism → behavior decided at the time of calling


Why Is It Useful?

  • You don’t repeat logic again and again.

  • You don’t care what type of account it is → as long as it has withdraw() method, your code will work.

  • You focus only on what to do, not how to do → that is the object’s job.


One Line Meaning:

Polymorphism lets you treat different objects in a similar way, but lets them act differently.

Updated on