Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
100% found this document useful (1 vote)
1K views

What Is Polymorphism in Python

Polymorphism in Python allows objects to take on multiple forms. It allows the same method to be called in different ways depending on the object's type or class. For example, the len() built-in function calculates length differently based on whether the object is a string or list. Polymorphism is also used with inheritance, where child classes can override methods from a parent class and define them specifically for the child class. This allows the same method name to behave differently based on the object, with Python determining the appropriate method to call based on the object's class.

Uploaded by

Mr Saem
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (1 vote)
1K views

What Is Polymorphism in Python

Polymorphism in Python allows objects to take on multiple forms. It allows the same method to be called in different ways depending on the object's type or class. For example, the len() built-in function calculates length differently based on whether the object is a string or list. Polymorphism is also used with inheritance, where child classes can override methods from a parent class and define them specifically for the child class. This allows the same method name to behave differently based on the object, with Python determining the appropriate method to call based on the object's class.

Uploaded by

Mr Saem
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 34

What is Polymorphism in Python?

Polymorphism in Python is the ability of an object to take many


forms. In simple words, polymorphism allows us to perform the
same action in many different ways.

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.
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.

The len() method treats an object as per its class type.

Example:

students = ['Emma', 'Jessa', 'Kelly']


school = 'ABC School'

# 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.

Using method overriding polymorphism allows us to defines


methods in the child class that have the same name as the
methods in the parent class. This process of re-implementing
the inherited method in the child class is known as Method
Overriding.
Advantage of method overriding

• It is effective when we want to extend the functionality


by altering the inherited method. Or the method
inherited from the parent class doesn’t fulfill the need of
a child class, so we need to re-implement the same
method in the child class in a different way.
• Method overriding is useful when a parent class has
multiple child classes, and one of that child class wants
to redefine the method. The other child classes can use
the parent class method. Due to this, we don’t need to
modification the parent class code
• In polymorphism, Python first checks the object’s class
type and executes the appropriate method when we call
the method. For example, If you create the Car object, then
Python calls the speed() method from a Car class.

• Let’s see how it works with the help of an example.

• Example: Method Overriding


• 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.

Polymorphism with Inheritance

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')

# inherit from vehicle class


class Car(Vehicle):
def max_speed(self):
print('Car max speed is 240')

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.

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.

What is Polymorphism in Python?

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.

Using method overriding polymorphism allows us to defines methods


in the child class that have the same name as the methods in the parent
class. This process of re-implementing the inherited method in the
child class is known as Method Overriding.

Advantage of method overriding


• It is effective when we want to extend the functionality by
altering the inherited method. Or the method inherited from
the parent class doesn’t fulfill the need of a child class, so we
need to re-implement the same method in the child class in a
different way.
• Method overriding is useful when a parent class has multiple
child classes, and one of that child class wants to redefine the
method. The other child classes can use the parent class
method. Due to this, we don’t need to modification the
parent class code
In polymorphism, Python first checks the object’s class type and
executes the appropriate method when we call the method. For
example, If you create the Car object, then Python calls
the speed() method from a Car class.

Let’s see how it works with the help of an example.

Example: Method Overriding

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.
Polymorphism with Inheritance

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')

# inherit from vehicle class


class Car(Vehicle):
def max_speed(self):
print('Car max speed is 240')

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:

Details: Car x1 Red 20000

Car max speed is 240

Car change 7 gear

Details: Truck x1 white 75000

Vehicle max speed is 150

Vehicle change 6 gear


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)

On the other hand, the show() method isn’t overridden in the Car class,
so it is used from the Vehicle class.

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

• 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

• Max speed 350

• Diesel

• Max speed is 240

• 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:

In this example, we create an Employee class by defining employee attributes


such as name and salary as an instance variable and implementing behavior
using work() and show() instance methods.

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)

# creating object of a class


emp = Employee('Jessa', 8000, 'NLP')

# calling public method of the class


emp.show()
emp.work()

Output:

Name: Jessa Salary: 8000

Jessa is working on NLP

Using encapsulation, we can hide an object’s internal representation from the


outside. This is called information hiding.

Also, encapsulation allows us to restrict accessing variables and methods directly


and prevent accidental data modification by creating private data members and
methods within a class.

Encapsulation is a way to can restrict access to methods and variables from


outside of class. Whenever we are working with the class and dealing with
sensitive data, providing access to all variables used within the class is not a good
choice.
For example, Suppose you have an attribute that is not visible from the outside of
an object and bundle it with methods that provide read or write access. In that
case, you can hide specific information and control access to the object’s internal
state. Encapsulation offers a way for us to access the required variable without
providing the program full-fledged access to all variables of a class. This
mechanism is used to protect the data of an object from other objects.

Access Modifiers in Python


Encapsulation can be achieved by declaring the data members and methods of a
class either as private or protected. But In Python, we don’t have direct access
modifiers like public, private, and protected. We can achieve this by using
single underscore and double underscores.

Access modifiers limit access to the variables and methods of a class. Python
provides three types of access modifiers private, public, and protected.

• Public Member: Accessible anywhere from outside of class.


• Private Member: Accessible within the class
• Protected Member: Accessible within the class and its sub-classes
Data hiding using access modifiers
By adding an underscore
Public Member
Public data members are accessible within and outside of a class. All member
variables of the class are by default public.

Example:

class Employee:
# constructor
def __init__(self, name, salary):
# public data members
self.name = name
self.salary = salary

# public instance methods


def show(self):
# accessing public data member
print("Name: ", self.name, 'Salary:', self.salary)

# creating object of a class


emp = Employee('Jessa', 10000)
# accessing public data members
print("Name: ", emp.name, 'Salary:', emp.salary)

# calling public method of the class


emp.show()

Run
Output

Name: Jessa Salary: 10000

Name: Jessa Salary: 10000

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

# creating object of a class


emp = Employee('Jessa', 10000)

# accessing private data members


print('Salary:', emp.__salary)

Output

AttributeError: 'Employee' object has no attribute '__salary'

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

• Create public method to access private members


• Use name mangling
Let’s see each one by one

Public method to access private members

Example: Access Private member outside of a class using an instance method

class Employee:
# constructor
def __init__(self, name, salary):
# public data member
self.name = name
# private member
self.__salary = salary

# public instance methods


def show(self):
# private members are accessible from a class
print("Name: ", self.name, 'Salary:', self.__salary)

# creating object of a class


emp = Employee('Jessa', 10000)
# calling public method of the class
emp.show()

Output:

Name: Jessa Salary: 10000

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.

Example: Proctecd member in inheritance.

# 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()

# Direct access protected data member


print('Project:', c._project)
Output

Employee name : Jessa

Working on project : NLP

Project: NLP

Getters and Setters in Python


To implement proper encapsulation in Python, we need to use setters and
getters. The primary purpose of using getters and setters in object-oriented
programs is to ensure data encapsulation. Use the getter method to access data
members and the setter methods to modify the data members.

In Python, private variables are not hidden fields like in other programming
languages. The getters and setters methods are often used when:

• When we want to avoid direct access to private variables


• To add validation logic for setting a value
• Example

• 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

• Let’s take another example that shows how to use encapsulation to


implement information hiding and apply additional validation before
changing the values of your object attributes (data member).

• Example: Information Hiding and conditional logic for setting an object


attributes

• 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:

Student Details: Jessa 10

Invalid roll no. Please set correct roll number

Student Details: Jessa 25


Advantages of Encapsulation
• Security: The main advantage of using encapsulation is the security
of the data. Encapsulation protects an object from unauthorized
access. It allows private and protected access levels to prevent
accidental data modification.
• Data Hiding: The user would not be knowing what is going on
behind the scene. They would only be knowing that to modify a data
member, call the setter method. To read a data member, call the
getter method. What these setter and getter methods are doing is
hidden from them.
• Simplicity: It simplifies the maintenance of the application by keeping
classes separated and preventing them from tightly coupling with
each other.
• Aesthetics: Bundling data and methods within a class makes code
more readable and maintainable
By added the ob.-Edureka—tech I will be able to access it now.

You might also like