2
Most read
9
Most read
www.datacademy.ai
Knowledge world
Learn Polymorphism in Python with Examples
Main Features Of Python include:
• Beginner-friendly Language – Python is easy to learn, maintain,
implement and read. It is interactive in nature.
• Object-Oriented – Python encapsulates code within objects by
supporting the Object-Oriented programming approach or style or
approach.
• Industry-oriented – Python is extendable, portable, scalable, cross-
platform friendly with a standard library, and has support for GUI
applications and interactive mode.
What is Polymorphism in Python?
In Python, polymorphisms refer to the occurrence of something in multiple
forms. As part of polymorphism, a Python child class has methods with the
same name as a parent class method. This is an essential part of
programming. A single type of entity is used to represent a variety of types in
different contexts (methods, operators, objects, etc.)
Polymorphism may be used in Python in various ways. Polymorphism can be
defined using numerous functions, class methods, and objects. So, let us deep-
dive into each of these ways.
Polymorphism With Function and Objects
To induce polymorphism using a function, we need to create such a function
that can take any object. Here is an example of Polymorphism using functions
and objects:
Code
class Dog():
def animal_kingdom(self):
print(“Mammal”)
def legs(self):
print(“Four”)
www.datacademy.ai
Knowledge world
class Lizard():
def animal_kingdom(self):
print(“Mammal”)
def legs(self):
print(“Four”)
def function1(obj):
obj.animal_kingdom()
obj.legs()
obj_dog = Dog()
obj_lizard = Lizard()
function1(obj_dog)
function1(obj_lizard)
Output
Mammal
Four
Mammal
Four
In the above example, the function, function1() takes in an object named obj,
which in turn lets the functions call the methods, animal_kingdom() and legs()
of both the classes, Dog and Lizard. To do this, we must create the instances of
both classes.
Polymorphism With Class Methods
www.datacademy.ai
Knowledge world
Let us discuss how to implement Polymorphism in Python using Class
Methods.
In the same way, Python makes use of two separate class types. For this, we
design a for loop that iterates through an item tuple. After that, we need to
perform method calling without regard for the class type of each object. We
take it for granted that these methods have their existence in each of the
classes.
A perfect example depicting Polymorphism with Class Methods using Python:
Code
class Car():
def wheels(self):
print(4)
def mode_of_transport(self):
print(“Private usually”)
class Bus():
def wheels(self):
print(8)
def mode_of_transport(self):
print(“Public usually”)
obj_car = Car()
obj_bus = Bus()
for vehicle in (obj_car, obj_bus):
vehicle.wheels()
www.datacademy.ai
Knowledge world
vehicle.mode_of_transport()
Output
4
Private usually
8
Public usually
In the above example, class methods wheels(), mode_of_transport(), which
belong to Car and Bus classes, are directly invoked using the instances of these
two classes in the for loop, which loops through both the class methods.
Polymorphism With Inheritance
Polymorphism, a child class method is allowed to have the same name as the
class methods in the parent class. In inheritance, the methods belonging to the
parent class are passed down to the child class. It’s also possible to change a
method that a child class has inherited from its parent.
This is typically used whenever a parent class inherited method is not
appropriate for the child class. To rectify this situation, we use Method
Overriding, which enables re-implementing of a method in a child class.
What Is Method Overriding?
Method overriding is an object-oriented programming technique that lets us
change the function implementation of a parent class in the child class.
Method overriding is basically a child class’s ability to implement change in
any method given by one of its parent classes.
Conditions of Method Overriding:
• There should be inheritance. Within a class, function overriding is not
possible, therefore a child class is derived from a parent class.
• A function of the child class should have the same number of parameters
as that of the parent class.
www.datacademy.ai
Knowledge world
We know that in inheritance, a child class gets access to the protected and
public methods and variables of the parent class whenever it inherits it. We
exploit this concept to implement Polymorphism using Inheritance as well.
A perfect example of Method Overriding and Polymorphism with Inheritance
is:
Code
class Vehicle:
def desc(self):
print(“So many categories of vehicle”)
def wheels(self):
print(“Differs according to the vehicle category”)
class car(Vehicle):
def wheels(self):
print(4)
class bus(Vehicle):
def wheel(self):
print(8)
obj_vehicle = Vehicle()
obj_car = car()
obj_bus = bus()
obj_vehicle.desc()
obj_vehicle.wheels()
www.datacademy.ai
Knowledge world
obj_car.desc()
obj_car.wheels()
obj_bus.desc()
obj_bus.wheels()
Output
So many categories of vehicle
Differs according to the vehicle category
So many categories of vehicle
4
So many categories of vehicle
Differs according to the vehicle category
Polymorphism is a concept in object-oriented programming where a single
function or method can operate on multiple types of objects. In Python,
polymorphism can be achieved through the use of inheritance and interfaces.
Here is an example of polymorphism using inheritance:
class Animal:
def __init__(self, name):
self.name = name
def speak(self):
pass
www.datacademy.ai
Knowledge world
class Dog(Animal):
def speak(self):
return "Woof"class Cat(Animal):
def speak(self):
return "Meow"def animal_speak(animal):
print(animal.speak())
dog = Dog("Fido")
cat = Cat("Whiskers")
animal_speak(dog) # "Woof"
animal_speak(cat) # "Me
In this example, the animal_speak function can take an object of any class
that inherits from the Animal class, and it will correctly call
the speak() method for that class.
You can also achieve polymorphism through the use of interfaces or abstract
base classes. Here’s an example:
www.datacademy.ai
Knowledge world
from abc import ABC, abstractmethod
class Shape(ABC):
@abstractmethoddef area(self):
passclass Square(Shape):
def __init__(self, side):
self.side = side
def area(self):
return self.side * self.side
class Circle(Shape):
def __init__(self, radius):
self.radius = radius
def area(self):
return 3.14 * (self.radius ** 2)
def get_shape_area(shape: Shape):
print(shape.area())
square = Square(4)
circle = Circle(5)
www.datacademy.ai
Knowledge world
get_shape_area(square) #16
get_shape_area(circle)
In this example, the get_shape_area function can take any object that is an
instance of the Shape class or any class that inherits from it, regardless of their
specific implementation of the area() method, and it will correctly call
the area() method for that class.

More Related Content

PPTX
arthimetic operator,classes,objects,instant
PPTX
Python-Polymorphism.pptx
PPTX
PYTHON OBJECT-ORIENTED PROGRAMMING.pptx
PPTX
Shuvrojit Majumder . 25900120006 Object Oriented Programming (PCC-CS 503) ...
PPTX
oops-in-python-240412044200-2d5c6552.pptx
PPTX
Polymorphism in Python
PDF
II BCA JAVA PROGRAMMING NOTES FOR FIVE UNITS.pdf
PDF
Object-Oriented Polymorphism Unleashed
arthimetic operator,classes,objects,instant
Python-Polymorphism.pptx
PYTHON OBJECT-ORIENTED PROGRAMMING.pptx
Shuvrojit Majumder . 25900120006 Object Oriented Programming (PCC-CS 503) ...
oops-in-python-240412044200-2d5c6552.pptx
Polymorphism in Python
II BCA JAVA PROGRAMMING NOTES FOR FIVE UNITS.pdf
Object-Oriented Polymorphism Unleashed

Similar to Learn Polymorphism in Python with Examples.pdf (20)

PPTX
Chapter 04 Object Oriented programming .pptx
PPTX
Polymorphism in Python
PPTX
OOPS 46 slide Python concepts .pptx
PPTX
Introduction to OOP concepts
PDF
PythonOO.pdf oo Object Oriented programming
PPTX
What is java polymorphism and its types in java training?
PPTX
Object Oriented Programming (OOP) Introduction
PPSX
Learn java objects inheritance-overriding-polymorphism
PDF
JAVA-PPT'S.pdf
PPTX
Object Oriented Programming.pptx
PDF
09. Ruby Object Oriented Programming - Ruby Core Teaching
PPTX
Object Oriented Programming
PPTX
Polymorphism in java
DOCX
Java OOPs Concepts.docx
PPTX
Lecture 5.pptx
PDF
Unit 3-Classes ,Objects and Inheritance.pdf
PPTX
Polymorphism
PDF
Java questions for interview
PPTX
Basics of oops concept
PPTX
OOP- PolymorphismFinal12injavait101.pptx
Chapter 04 Object Oriented programming .pptx
Polymorphism in Python
OOPS 46 slide Python concepts .pptx
Introduction to OOP concepts
PythonOO.pdf oo Object Oriented programming
What is java polymorphism and its types in java training?
Object Oriented Programming (OOP) Introduction
Learn java objects inheritance-overriding-polymorphism
JAVA-PPT'S.pdf
Object Oriented Programming.pptx
09. Ruby Object Oriented Programming - Ruby Core Teaching
Object Oriented Programming
Polymorphism in java
Java OOPs Concepts.docx
Lecture 5.pptx
Unit 3-Classes ,Objects and Inheritance.pdf
Polymorphism
Java questions for interview
Basics of oops concept
OOP- PolymorphismFinal12injavait101.pptx
Ad

More from Datacademy.ai (16)

PDF
Characteristics of Big Data Understanding the Five V.pdf
PDF
Why Monitoring and Logging are Important in DevOps.pdf
PDF
AWS data storage Amazon S3, Amazon RDS.pdf
PDF
Top 30+ Latest AWS Certification Interview Questions on AWS BI and data visua...
PDF
Top 50 Ansible Interview Questions And Answers in 2023.pdf
PDF
Interview Questions on AWS Elastic Compute Cloud (EC2).pdf
PDF
50 Extraordinary AWS CloudWatch Interview Questions & Answers.pdf
PDF
Top 30+ Latest AWS Certification Interview Questions on AWS BI & Data Visuali...
PDF
Top 60 Power BI Interview Questions and Answers for 2023.pdf
PDF
Top 100+ Google Data Science Interview Questions.pdf
PDF
AWS DevOps: Introduction to DevOps on AWS
PDF
Data Engineering.pdf
PDF
Top 140+ Advanced SAS Interview Questions and Answers.pdf
PDF
50 Extraordinary AWS CloudWatch Interview Questions & Answers.pdf
PDF
Top 60+ Data Warehouse Interview Questions and Answers.pdf
PDF
Top Most Python Interview Questions.pdf
Characteristics of Big Data Understanding the Five V.pdf
Why Monitoring and Logging are Important in DevOps.pdf
AWS data storage Amazon S3, Amazon RDS.pdf
Top 30+ Latest AWS Certification Interview Questions on AWS BI and data visua...
Top 50 Ansible Interview Questions And Answers in 2023.pdf
Interview Questions on AWS Elastic Compute Cloud (EC2).pdf
50 Extraordinary AWS CloudWatch Interview Questions & Answers.pdf
Top 30+ Latest AWS Certification Interview Questions on AWS BI & Data Visuali...
Top 60 Power BI Interview Questions and Answers for 2023.pdf
Top 100+ Google Data Science Interview Questions.pdf
AWS DevOps: Introduction to DevOps on AWS
Data Engineering.pdf
Top 140+ Advanced SAS Interview Questions and Answers.pdf
50 Extraordinary AWS CloudWatch Interview Questions & Answers.pdf
Top 60+ Data Warehouse Interview Questions and Answers.pdf
Top Most Python Interview Questions.pdf
Ad

Recently uploaded (20)

PDF
MBA _Common_ 2nd year Syllabus _2021-22_.pdf
PPTX
DRUGS USED FOR HORMONAL DISORDER, SUPPLIMENTATION, CONTRACEPTION, & MEDICAL T...
PPTX
Introduction to pro and eukaryotes and differences.pptx
PDF
BP 505 T. PHARMACEUTICAL JURISPRUDENCE (UNIT 1).pdf
PDF
LIFE & LIVING TRILOGY- PART (1) WHO ARE WE.pdf
PDF
BP 505 T. PHARMACEUTICAL JURISPRUDENCE (UNIT 2).pdf
DOCX
Cambridge-Practice-Tests-for-IELTS-12.docx
PDF
Empowerment Technology for Senior High School Guide
PPTX
Computer Architecture Input Output Memory.pptx
PDF
Race Reva University – Shaping Future Leaders in Artificial Intelligence
PPTX
What’s under the hood: Parsing standardized learning content for AI
PPTX
ELIAS-SEZIURE AND EPilepsy semmioan session.pptx
PDF
Skin Care and Cosmetic Ingredients Dictionary ( PDFDrive ).pdf
PDF
English Textual Question & Ans (12th Class).pdf
PPTX
Climate Change and Its Global Impact.pptx
PDF
LEARNERS WITH ADDITIONAL NEEDS ProfEd Topic
PDF
FORM 1 BIOLOGY MIND MAPS and their schemes
PDF
Τίμαιος είναι φιλοσοφικός διάλογος του Πλάτωνα
PDF
Complications of Minimal Access-Surgery.pdf
PDF
BP 704 T. NOVEL DRUG DELIVERY SYSTEMS (UNIT 1)
MBA _Common_ 2nd year Syllabus _2021-22_.pdf
DRUGS USED FOR HORMONAL DISORDER, SUPPLIMENTATION, CONTRACEPTION, & MEDICAL T...
Introduction to pro and eukaryotes and differences.pptx
BP 505 T. PHARMACEUTICAL JURISPRUDENCE (UNIT 1).pdf
LIFE & LIVING TRILOGY- PART (1) WHO ARE WE.pdf
BP 505 T. PHARMACEUTICAL JURISPRUDENCE (UNIT 2).pdf
Cambridge-Practice-Tests-for-IELTS-12.docx
Empowerment Technology for Senior High School Guide
Computer Architecture Input Output Memory.pptx
Race Reva University – Shaping Future Leaders in Artificial Intelligence
What’s under the hood: Parsing standardized learning content for AI
ELIAS-SEZIURE AND EPilepsy semmioan session.pptx
Skin Care and Cosmetic Ingredients Dictionary ( PDFDrive ).pdf
English Textual Question & Ans (12th Class).pdf
Climate Change and Its Global Impact.pptx
LEARNERS WITH ADDITIONAL NEEDS ProfEd Topic
FORM 1 BIOLOGY MIND MAPS and their schemes
Τίμαιος είναι φιλοσοφικός διάλογος του Πλάτωνα
Complications of Minimal Access-Surgery.pdf
BP 704 T. NOVEL DRUG DELIVERY SYSTEMS (UNIT 1)

Learn Polymorphism in Python with Examples.pdf

  • 1. www.datacademy.ai Knowledge world Learn Polymorphism in Python with Examples Main Features Of Python include: • Beginner-friendly Language – Python is easy to learn, maintain, implement and read. It is interactive in nature. • Object-Oriented – Python encapsulates code within objects by supporting the Object-Oriented programming approach or style or approach. • Industry-oriented – Python is extendable, portable, scalable, cross- platform friendly with a standard library, and has support for GUI applications and interactive mode. What is Polymorphism in Python? In Python, polymorphisms refer to the occurrence of something in multiple forms. As part of polymorphism, a Python child class has methods with the same name as a parent class method. This is an essential part of programming. A single type of entity is used to represent a variety of types in different contexts (methods, operators, objects, etc.) Polymorphism may be used in Python in various ways. Polymorphism can be defined using numerous functions, class methods, and objects. So, let us deep- dive into each of these ways. Polymorphism With Function and Objects To induce polymorphism using a function, we need to create such a function that can take any object. Here is an example of Polymorphism using functions and objects: Code class Dog(): def animal_kingdom(self): print(“Mammal”) def legs(self): print(“Four”)
  • 2. www.datacademy.ai Knowledge world class Lizard(): def animal_kingdom(self): print(“Mammal”) def legs(self): print(“Four”) def function1(obj): obj.animal_kingdom() obj.legs() obj_dog = Dog() obj_lizard = Lizard() function1(obj_dog) function1(obj_lizard) Output Mammal Four Mammal Four In the above example, the function, function1() takes in an object named obj, which in turn lets the functions call the methods, animal_kingdom() and legs() of both the classes, Dog and Lizard. To do this, we must create the instances of both classes. Polymorphism With Class Methods
  • 3. www.datacademy.ai Knowledge world Let us discuss how to implement Polymorphism in Python using Class Methods. In the same way, Python makes use of two separate class types. For this, we design a for loop that iterates through an item tuple. After that, we need to perform method calling without regard for the class type of each object. We take it for granted that these methods have their existence in each of the classes. A perfect example depicting Polymorphism with Class Methods using Python: Code class Car(): def wheels(self): print(4) def mode_of_transport(self): print(“Private usually”) class Bus(): def wheels(self): print(8) def mode_of_transport(self): print(“Public usually”) obj_car = Car() obj_bus = Bus() for vehicle in (obj_car, obj_bus): vehicle.wheels()
  • 4. www.datacademy.ai Knowledge world vehicle.mode_of_transport() Output 4 Private usually 8 Public usually In the above example, class methods wheels(), mode_of_transport(), which belong to Car and Bus classes, are directly invoked using the instances of these two classes in the for loop, which loops through both the class methods. Polymorphism With Inheritance Polymorphism, a child class method is allowed to have the same name as the class methods in the parent class. In inheritance, the methods belonging to the parent class are passed down to the child class. It’s also possible to change a method that a child class has inherited from its parent. This is typically used whenever a parent class inherited method is not appropriate for the child class. To rectify this situation, we use Method Overriding, which enables re-implementing of a method in a child class. What Is Method Overriding? Method overriding is an object-oriented programming technique that lets us change the function implementation of a parent class in the child class. Method overriding is basically a child class’s ability to implement change in any method given by one of its parent classes. Conditions of Method Overriding: • There should be inheritance. Within a class, function overriding is not possible, therefore a child class is derived from a parent class. • A function of the child class should have the same number of parameters as that of the parent class.
  • 5. www.datacademy.ai Knowledge world We know that in inheritance, a child class gets access to the protected and public methods and variables of the parent class whenever it inherits it. We exploit this concept to implement Polymorphism using Inheritance as well. A perfect example of Method Overriding and Polymorphism with Inheritance is: Code class Vehicle: def desc(self): print(“So many categories of vehicle”) def wheels(self): print(“Differs according to the vehicle category”) class car(Vehicle): def wheels(self): print(4) class bus(Vehicle): def wheel(self): print(8) obj_vehicle = Vehicle() obj_car = car() obj_bus = bus() obj_vehicle.desc() obj_vehicle.wheels()
  • 6. www.datacademy.ai Knowledge world obj_car.desc() obj_car.wheels() obj_bus.desc() obj_bus.wheels() Output So many categories of vehicle Differs according to the vehicle category So many categories of vehicle 4 So many categories of vehicle Differs according to the vehicle category Polymorphism is a concept in object-oriented programming where a single function or method can operate on multiple types of objects. In Python, polymorphism can be achieved through the use of inheritance and interfaces. Here is an example of polymorphism using inheritance: class Animal: def __init__(self, name): self.name = name def speak(self): pass
  • 7. www.datacademy.ai Knowledge world class Dog(Animal): def speak(self): return "Woof"class Cat(Animal): def speak(self): return "Meow"def animal_speak(animal): print(animal.speak()) dog = Dog("Fido") cat = Cat("Whiskers") animal_speak(dog) # "Woof" animal_speak(cat) # "Me In this example, the animal_speak function can take an object of any class that inherits from the Animal class, and it will correctly call the speak() method for that class. You can also achieve polymorphism through the use of interfaces or abstract base classes. Here’s an example:
  • 8. www.datacademy.ai Knowledge world from abc import ABC, abstractmethod class Shape(ABC): @abstractmethoddef area(self): passclass Square(Shape): def __init__(self, side): self.side = side def area(self): return self.side * self.side class Circle(Shape): def __init__(self, radius): self.radius = radius def area(self): return 3.14 * (self.radius ** 2) def get_shape_area(shape: Shape): print(shape.area()) square = Square(4) circle = Circle(5)
  • 9. www.datacademy.ai Knowledge world get_shape_area(square) #16 get_shape_area(circle) In this example, the get_shape_area function can take any object that is an instance of the Shape class or any class that inherits from it, regardless of their specific implementation of the area() method, and it will correctly call the area() method for that class.