What Is Polymorphism in Python
What Is Polymorphism in Python
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.
Polymorphism in Built-in function len()
The built-in function len() calculates the length of an object
depending upon its type. If an object is a string, it returns the
count of characters, and If an object is a list, it returns the count of
items in a list.
Example:
# calculate count
print(len(students))
print(len(school))
Output
10
Polymorphism With Inheritance
Polymorphism is mainly used with inheritance. In inheritance,
child class inherits the attributes and methods of a parent class.
The existing class is called a base class or parent class, and the
new class is called a subclass or child class or derived class.
class Vehicle:
def __init__(self, name, color, price):
self.name = name
self.color = color
self.price = price
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()
Polymorphism in Python
Object-Oriented Programming (OOP) has four essential characteristics:
abstraction, encapsulation, inheritance, and polymorphism.
class Vehicle:
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:
On the other hand, the show() method isn’t overridden in the Car class,
so it is used from the Vehicle 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
• In the below example, fuel_type() and max_speed() are the instance methods
created in both classes.
• 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()
•
• # iterate objects of same type
• for car in (ferrari, bmw):
• # call methods without checking class of object
• car.fuel_type()
• car.max_speed()
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.
Encapsulation in Python
Encapsulation in Python describes the concept of bundling data
and methods within a single unit. So, for example, when you create a class, it
means you are implementing encapsulation. A class is an example of
encapsulation as it binds all the data members (instance variables) and methods
into a single unit.
Example:
class Employee:
# constructor
def __init__(self, name, salary, project):
# data members
self.name = name
self.salary = salary
self.project = project
# method
# to display employee's details
def show(self):
# accessing public data member
print("Name: ", self.name, 'Salary:', self.salary)
# method
def work(self):
print(self.name, 'is working on', self.project)
Output:
Access modifiers limit access to the variables and methods of a class. Python
provides three types of access modifiers private, public, and protected.
Example:
class Employee:
# constructor
def __init__(self, name, salary):
# public data members
self.name = name
self.salary = salary
Run
Output
Private Member
We can protect variables in the class by marking them private. To define a private
variable add two underscores as a prefix at the start of a variable name.
Private members are accessible only within the class, and we can’t access them
directly from the class objects.
Example:
class Employee:
# constructor
def __init__(self, name, salary):
# public data member
self.name = name
# private member
self.__salary = salary
Output
In the above example, the salary is a private variable. As you know, we can’t
access the private variable from the outside of that class.
We can access private members from outside of a class using the following two
approaches
class Employee:
# constructor
def __init__(self, name, salary):
# public data member
self.name = name
# private member
self.__salary = salary
Output:
Protected Member
Protected members are accessible within the class and also available to its sub-
classes. To define a protected member, prefix the member name with a single
underscore _.
Protected data members are used when you implement inheritance and want to
allow data members access to only child classes.
# base class
class Company:
def __init__(self):
# Protected member
self._project = "NLP"
# child class
class Employee(Company):
def __init__(self, name):
self.name = name
Company.__init__(self)
def show(self):
print("Employee name :", self.name)
# Accessing protected member in child class
print("Working on project :", self._project)
c = Employee("Jessa")
c.show()
Project: NLP
In Python, private variables are not hidden fields like in other programming
languages. The getters and setters methods are often used when:
• class Student:
• def __init__(self, name, age):
• # private member
• self.name = name
• self.__age = age
•
• # getter method
• def get_age(self):
• return self.__age
•
• # setter method
• def set_age(self, age):
• self.__age = age
•
• stud = Student('Jessa', 14)
•
• # retrieving age using getter
• print('Name:', stud.name, stud.get_age())
•
• # changing age using setter
• stud.set_age(16)
•
• # retrieving age using getter
• print('Name:', stud.name, stud.get_age())
• Output
• Name: Jessa 14
• Name: Jessa 16
• class Student:
• def __init__(self, name, roll_no, age):
• # private member
• self.name = name
• # private members to restrict access
• # avoid direct data modification
• self.__roll_no = roll_no
• self.__age = age
•
• def show(self):
• print('Student Details:', self.name,
self.__roll_no)
•
• # getter methods
• def get_roll_no(self):
• return self.__roll_no
•
• # setter method to modify data member
• # condition to allow data modification with rules
• def set_roll_no(self, number):
• if number > 50:
• print('Invalid roll no. Please set correct
roll number')
• else:
• self.__roll_no = number
•
• jessa = Student('Jessa', 10, 15)
• # before Modify
• jessa.show()
• # changing roll number using setter
• jessa.set_roll_no(120)
• jessa.set_roll_no(25)
• jessa.show()
Output: