Polymorphism in Python
Polymorphism in Python
This lesson will cover what polymorphism is and how to implement them in
Python. Also, you’ll learn how to implement polymorphism using function
overloading, method overriding, and operator overloading.
Table of contents
What is Polymorphism in Python?
For example, Jessa acts as an employee when she is at the office. However,
when she is at home, she acts like a wife. Also, she represents herself
differently in different places. Therefore, the same person takes different forms
as per the situation.
A person
takes different forms
In polymorphism, a method can process objects differently depending on
the class type or data type. Let’s see simple examples to understand it better.
Example:
# calculate count
print(len(students))
print(len(school))
Run
Output
3
10
In this example, we have a vehicle class as a parent and a ‘Car’ and ‘Truck’ as
its sub-class. But each vehicle can have a different seating capacity, speed, etc.,
so we can have the same instance method name in each class but with a
different implementation. Using this code can be extended and easily
maintained over time.
def show(self):
print('Details:', self.name, self.color, self.price)
def max_speed(self):
print('Vehicle max speed is 150')
def change_gear(self):
print('Vehicle change 6 gear')
def change_gear(self):
print('Car change 7 gear')
# Car Object
car = Car('Car x1', 'Red', 20000)
car.show()
# calls methods from Car class
car.max_speed()
car.change_gear()
# Vehicle Object
vehicle = Vehicle('Truck x1', 'white', 75000)
vehicle.show()
# calls method from a Vehicle class
vehicle.max_speed()
vehicle.change_gear()
Run
Output:
As you can see, due to polymorphism, the Python interpreter recognizes that
the max_speed() and change_gear() methods are overridden for the car object. So,
it uses the one defined in the child class (Car)
In Python, we can change the default behavior of the built-in functions. For
example, we can change or extend the built-in functions such as len(), abs(),
or divmod() by redefining them in our class. Let’s see the example.
Example
class Shopping:
def __init__(self, basket, buyer):
self.basket = list(basket)
self.buyer = buyer
def __len__(self):
print('Redefine length')
count = len(self.basket)
# count total items in a different way
# pair of shoes and shir+pant
return count * 2
Run
Output
Redefine length
4
Polymorphism In Class methods
Polymorphism with class methods is useful when we group different objects
having the same method. we can add them to a list or a tuple, and we don’t
need to check the object type before calling their methods. Instead, Python
will check object type at runtime and call the correct method. Thus, we can call
the methods without being concerned about which class type each object is.
We assume that these methods exist in each class.
Python allows different classes to have methods with the same name.
Let’s design a different class in the same way by adding the same
methods in two or more classes.
Next, create an object of each class
Next, add all objects in a tuple.
In the end, iterate the tuple using a for loop and call methods of a
object without checking its class.
Example
class Ferrari:
def fuel_type(self):
print("Petrol")
def max_speed(self):
print("Max speed 350")
class BMW:
def fuel_type(self):
print("Diesel")
def max_speed(self):
print("Max speed is 240")
ferrari = Ferrari()
bmw = BMW()
Run
Output
Petrol
Diesel
As you can see, we have created two classes Ferrari and BMW. They have the
same instance method names fuel_type() and max_speed(). However, we have
not linked both the classes nor have we used inheritance.
We packed two different objects into a tuple and iterate through it using a car
variable. It is possible due to polymorphism because we have added the same
method in both classes Python first checks the object’s class type and executes
the method present in its class.
Example
class Ferrari:
def fuel_type(self):
print("Petrol")
def max_speed(self):
print("Max speed 350")
class BMW:
def fuel_type(self):
print("Diesel")
def max_speed(self):
print("Max speed is 240")
# normal function
def car_details(obj):
obj.fuel_type()
obj.max_speed()
ferrari = Ferrari()
bmw = BMW()
car_details(ferrari)
car_details(bmw)
Run
Output
Petrol
Diesel
Let us see how a built-in method process objects having different data types.
Example:
students = ['Emma', 'Jessa', 'Kelly']
school = 'ABC School'
print('Reverse string')
for i in reversed('PYnative'):
print(i, end=' ')
print('\nReverse list')
for i in reversed(['Emma', 'Jessa', 'Kelly']):
print(i, end=' ')
Run
Output:
Reverse string
e v i t a n Y P
Reverse list
Method Overloading
The process of calling the same method with different parameters is known as
method overloading. Python does not support method overloading. Python
considers only the latest defined method even if you overload the method.
Python will raise a TypeError if you overload the method.
Example
Run
To overcome the above problem, we can use different ways to achieve the
method overloading. In Python, to overload the class method, we need to
write the method’s logic so that different code executes inside the function
depending on the parameter passes.
Example:
Run
Output:
0, 1, 2, 3, 4,
5, 6, 7, 8, 9,
2, 4, 6, 8, 10,
square = Shape()
square.area(5)
rectangle = Shape()
rectangle.area(5, 3)
Run
Output:
The operator + is used to carry out different operations for distinct data types.
This is one of the most simple occurrences of polymorphism in Python.
Example:
# add 2 numbers
print(100 + 200)
Run
Output:
300
JessRoy
Suppose we have two objects, and we want to add these two objects with a
binary + operator. However, it will throw an error if we perform addition
because the compiler doesn’t add two objects. See the following example for
more details.
Example:
class Book:
def __init__(self, pages):
self.pages = pages
Run
Output
Example:
class Book:
def __init__(self, pages):
self.pages = pages
b1 = Book(400)
b2 = Book(300)
print("Total number of pages: ", b1 + b2)
Run
Output
Overloading the * Operator
Example:
class Employee:
def __init__(self, name, salary):
self.name = name
self.salary = salary
class TimeSheet:
def __init__(self, name, days):
self.name = name
self.days = days
Run
Output
Magic Methods
magic methods
Filed Under: Python , Python Object-Oriented Programming (OOP)