Polymorphism OOPs In Python

Polymorphism In OOPs Python scaled Explore and Read Our Blogs Written By Our Insutry Experts Learn From KSR Data Vizon

Polymorphism is an object-oriented programming concept that means “one function, many forms”. In Python, it allows the same method name to be used for different types of objects, and the behavior will depend on the object’s class.

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

Conclusion

Polymorphism is a powerful feature in Python that enhances flexibility and allows for writing more generic code. By using duck typing, overloading, and overriding, developers can create the applications that are easier to maintain and extend.

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 *