UNIT 5 - Polymorphism
UNIT 5 - Polymorphism
Types of Polymorphism
Method Overriding:
class Animal:
def make_sound(self):
print("Some generic animal sound")
class Dog(Animal):
def make_sound(self):
print("Woof!")
class Cat(Animal):
def make_sound(self):
print("Meow!")
def animal_sound(animal):
animal.make_sound()
Python doesn’t support true method overloading, but we can simulate it by using default
arguments.
class Calculator:
def add(self, a, b=0, c=0):
return a + b + c
# Creating object
calc = Calculator()
Output:
Hello, World!
Hello, Python!
Operator Overloading
Python also supports operator overloading, which allows us to redefine the behavior of operators
such as +, -, *, etc. when working with objects of a custom class.
we can define special methods like __add__, __sub__, __mul__, etc., to control how these
operators (+, -, *) behave with our objects.
Overload the + operator to add two Point objects together, meaning that adding two points will
add their respective x and y coordinates.
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
def __str__(self):
return f"Point({self.x}, {self.y})"
Output:
The two points are added by using the overloaded '+' operator
Point(4, 6)
Note:
__str__ method is a built-in magic method in Python that is used to define a human-readable
string representation of an object.
The __str__ method is not strictly required for operator overloading, but it is often used to make
objects easier to print and inspect in a readable way.
Benefits of Polymorphism
Code Reusability: You can use a single function to process objects of different classes.
Flexibility: New classes can be added with minimal changes to the code.
Maintenance: Easier to maintain and extend.
Polymorphism is a powerful feature that helps in writing cleaner and more efficient code.