Notes
Categories

Polymorphism in Python [ English ]

< Prev Next >

1. Introduction

Polymorphism is one of the core concepts of Object-Oriented Programming (OOP). The word polymorphism means “many forms”.

In Python, polymorphism allows the same function or method name to behave differently depending on the object or data it is used with.

2. Definition

Polymorphism is:

The ability of a function, method, or operator to perform different tasks based on the context.

3. Types of Polymorphism in Python

  1. Function (Built-in) Polymorphism
  2. Operator Polymorphism
  3. Method Overriding (Runtime Polymorphism)
  4. (Note: Python does not support true method overloading like some languages, but similar behavior can be achieved)

4. Function Polymorphism

Example

print(len("Hello"))      # String length
print(len([1, 2, 3]))   # List length

Output

5
3

Explanation

5. Operator Polymorphism

Example

print(2 + 3)        # Addition
print("Hello " + "World")  # String concatenation

Output

5
Hello World

Explanation


6. Method Overriding (Runtime Polymorphism)

6.1 Definition

When a child class provides its own implementation of a method that is already defined in the parent class.

6.2 Example

class Animal:
    def sound(self):
        print("Animal makes sound")

class Dog(Animal):
    def sound(self):
        print("Dog barks")

class Cat(Animal):
    def sound(self):
        print("Cat meows")

a = Animal()
d = Dog()
c = Cat()

a.sound()
d.sound()
c.sound()

Output

Animal makes sound
Dog barks
Cat meows

7. Method Overloading (Limited in Python)

Python does not support traditional method overloading, but it can be achieved using default arguments.

Example

def add(a, b=0, c=0):
    return a + b + c

print(add(2, 3))
print(add(2, 3, 4))

8. Duck Typing

Python follows duck typing, which is a form of polymorphism.

“If it looks like a duck and behaves like a duck, it is treated as a duck.”

Example

class Dog:
    def speak(self):
        print("Bark")

class Cat:
    def speak(self):
        print("Meow")

def make_sound(animal):
    animal.speak()

make_sound(Dog())
make_sound(Cat())

9. Advantages of Polymorphism

10. Summary

< Prev Next >