Polymorphism OOPs In Python

Polymorphism is one of the four main principles of Object-Oriented Programming (OOP). It allows one interface to work with different object types. As a result, your code becomes flexible, reusable, and easier to maintain.

For example, different animals can respond to the same sound() method in their own way. Similarly, different payment methods can use the same pay() method but perform different actions. This concept helps developers write cleaner applications with less duplicate code.

What is Polymorphism?

The word polymorphism means “many forms.”

In Python, it means the same method, function, or operator behaves differently depending on the object that uses it.

Simply put:

One method name → Multiple implementations

Examples of Polymorphism: Operators

  • + acts as both concatenation and arithmetic addition.
  • * serves as multiplication and repetition.

Key Concepts

  • Duck Typing Philosophy
  • Overloading:
    • Method Overloading
    • Operator Overloading
    • Constructor Overloading
  • Overriding:
    • Method Overriding
    • Constructor Overriding

Duck Typing Philosophy of Python

Duck typing means that instead of checking an object’s type explicitly, you just use it as long as it behaves the way you expect. If an object implements the required behavior (like specific methods), it’s treated as suitable—regardless of its class.

Example:

class Dog:
    def sound(self):
        return "Bark"

class Cat:
    def sound(self):
        return "Meow"

def animal_sound(animal):
    print(animal.sound())

dog = Dog()
cat = Cat()

animal_sound(dog)
animal_sound(cat)

Output:

Bark
Meow

In this example, both the Dog and Cat classes have a sound() method. The animal_sound() function can accept any object that implements a sound() method, regardless of its class.

Overloading

It allows methods and operators to perform differently based on the inputs.

Method Overloading

Python does not natively support method overloading, but you can mimic this behavior using default or variable-length arguments.

Example:

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

math = Math()
print(math.add(2, 3))
print(math.add(2, 3, 4))

Output:

5
9

Operator Overloading

Python enables you to specify the behavior of operators for custom classes by defining special methods.

Example:

class Vector:
    def __init__(self, x, y):
        self.x = x
        self.y = y

    def __add__(self, other):
        return Vector(self.x + other.x, self.y + other.y)

    def __str__(self):
        return f"({self.x}, {self.y})"

v1 = Vector(2, 3)
v2 = Vector(5, 7)
v3 = v1 + v2
print(v3)

Output:

(7, 10)

Constructor Overloading

Python does not support constructor overloading directly, but it can be implemented using default or variable-length arguments

Example:

class Person:
    def __init__(self, name, age=None):
        self.name = name
        self.age = age

    def display(self):
        if self.age:
            return f"{self.name} is {self.age} years old."
        return f"{self.name} has no age provided."

person1 = Person("Alice")
person2 = Person("Bob", 30)

print(person1.display())
print(person2.display())

Output:

Alice has no age provided.
Bob is 30 years old.

Overriding

It allows a sub-class to provide a specific implementations of a method that is already defined in its superclass.

Method Overriding

When a subclass defines a method that already exists in its superclass, it overrides the method of the superclass.

Example:

class Animal:
    def speak(self):
        return "Animal speaks"

class Dog(Animal):
    def speak(self):  # Overriding the speak method
        return "Bark"

dog = Dog()
print(dog.speak())

Output:

Bark

Constructor Overriding

A subclass can also override the constructor of its superclass using the super() function to call the parent class’s constructor.

Example:

class Vehicle:
    def __init__(self, name):
        self.name = name

class Car(Vehicle):
    def __init__(self, name, model):
        super().__init__(name)  # Calling parent constructor
        self.model = model

car = Car("Toyota", "Corolla")
print(car.name)
print(car.model)

Output:

Toyota
Corolla

What is polymorphism in Python?

Polymorphism allows one method, function, or operator to perform different actions depending on the object or data type.

Why is polymorphism important?

It improves code reuse, flexibility, and maintainability.

Does Python support method overloading?

Python does not support true compile-time method overloading. Similar behavior can be achieved using default arguments or variable-length arguments.

What is duck typing?

Duck typing allows objects with the required methods to be used without checking their exact class.

Conclusion

Polymorphism is a core feature of Object-Oriented Programming in Python. It allows the same interface to perform different actions based on the object being used. As a result, your programs become more flexible, reusable, and easier to maintain. By combining polymorphism with inheritance, abstraction, and encapsulation, you can build clean and scalable Python applications.

Knowledge Check

Related Article No.4

https://blog.ksrdatavision.com/python/input-and-output-in-python
Data Analytics with Power Bi and Fabric
Could Data Engineer
Data Analytics With Power Bi Fabic
AWS Data Engineering with Snowflake
Azure Data Engineering
Azure & Fabric for Power bi
Full Stack Power Bi
Subscribe to our channel & Don’t miss any update on trending technologies

Kick Start Your Career With Our Data Job

Master Fullstack Power BI – SQL, Power BI, Azure Cloud & Fabric Tools
Master in Data Science With Generative AI Transform Data into Business Solutions
Master Azure Data Engineering – Build Scalable Solutions for Big Data
Master AWS Data Engineering with Snowflake: Build Scalable Data Solutions
Transform Your Productivity With Low Code Technology: Master the Microsoft Power Platform

Social Media channels

► KSR Datavizon Website :- https://www.datavizon.com
► KSR Datavizon LinkedIn :- https://www.linkedin.com/company/datavizon/
► KSR Datavizon You tube :- https://www.youtube.com/c/KSRDatavizon
► KSR Datavizon Twitter :- https://twitter.com/ksrdatavizo

Related Posts

Leave a Reply

Your email address will not be published. Required fields are marked *