Lecture 7
Lecture 7
Omar Yahya
Lecture 7
Polymorphism
Polymorphism is a popular concept in object-oriented programming (OOP), referring to the idea
that an entity in code such as a variable, function or object can have more than one form. The word
polymorphism is derived from Greek and means "having multiple forms." Apart from computer
programming, the idea of polymorphism occurs in other real-world areas, including biology,
chemistry and drug development.
Assume there is a person who can have many qualities or relationships at the same time. As in, the
person is a father, a brother, a husband, and an employee all at the same time. As a result, the same
person exhibits diverse behavior in different settings.
Polymorphism is one of the most important concepts in OOP. It describes the ability of something
to have or to be displayed in more than one form. The different forms arise because these entities
can be assigned different meanings and used in various ways in multiple contexts.
Many programming languages display or allow polymorphism, including Java, Ruby, C++, PHP
and Python. In these languages, polymorphism enables class objects belonging to the same
hierarchical tree to behave differently, even though they might have functions with the same name.
Figure 1: Polymorphism.
Types of polymorphism:
• Runtime Polymorphism:
This type of polymorphism occurs at runtime. The dynamic behavior of the program is determined
by the type of the actual object being manipulated during program execution.
• Compile-time Polymorphism:
1
OOP in Python Eng. Omar Yahya
This type of polymorphism occurs at compile time (when the code is compiled). In languages that
support compile-time polymorphism, the correct method or operation is determined based on the
types specified at compile time.
Function Overloading:
Function overloading means having multiple functions with the same name but different
parameters. Which function is called is determined by the type and number of parameters.
In Python, Python does not support function overloading directly as languages like C++ or Java
do, but the same efficiency can be achieved by using parameters with default values or writing
functions that accept an unlimited number of parameters.
Operator Overloading:
Overloading operations means that the same arithmetic operation (such as +, -, *, /) can have
different behavior depending on different types of objects.
In Python, Python has extensive support for overloading operations. For example, the addition
operation + can be overloaded to work with user-defined objects.
Virtual Functions:
Virtual functions are functions that are defined in the base class and overridden in derived
classes. At runtime, the correct function is called based on the type of object that calls it.
In Python, every function in the base class can be considered virtual by default, as it can be
overridden in derived classes.
2
OOP in Python Eng. Omar Yahya
Advantages of Polymorphism:
1. Code Reusability.
2. Code Flexibility and Extensibility.
3. Saves a lot of time for the programmers.
4. Simplified Code Structure.
5. Improved Maintainability.
6. Easy to debug the codes.
num1 = 1
num2 = 2
print(num1+num2) # Output=> 3
Similarly, for string data types, + operator is used to perform concatenation.
str1 = "Python"
str2 = "Programming"
print(str1+" "+str2) # Output=> Python Programming
3
OOP in Python Eng. Omar Yahya
Here, we can see that a single operator + has been used to carry out different operations for distinct
data types. This is one of the simplest occurrences of polymorphism in Python.
print(len("Programiz")) # Output=> 9
print(len(["Python", "Java", "C"])) # Output=> 3
print(len({"Name": "John", "Address": "Nepal"})) # Output=> 2
Here, we can see that many data types such as string, list, tuple, set, and dictionary can work with
the len() function. However, we can see that it returns specific information about specific data
types.
4
OOP in Python Eng. Omar Yahya
class Duck:
def quack(self):
print("Quack!")
class Person:
def quack(self):
print("I can't quack like a duck, but I can try!")
Code Description
Class Definition:
Duck: Contains a quack method that prints "Quack!".
Person: Also contains a quack method, but it prints a different text.
Make_quack:
This method takes an object as input and calls the quack method on it.
Make_quack doesn't care which class the object comes from; all that matters is that the object has
a quack method.
Creating objects and calling the method:
An object is created from the Duck class and another object from the Person class.
5
OOP in Python Eng. Omar Yahya
When make_quack is called with the duck object, Duck's quack method is called, which prints
"Quack!".
When make_quack is called with the person object, Person's quack method is called, which
prints "I can't quack like a duck, but I can try!".
Duck Typing:
This term refers to a programming concept that means that an object's type is determined by the
way it behaves, not necessarily by inheriting from a particular class.
In Python, this means that if an object behaves like a duck (has a quack function), it can be treated
as a duck.
6
OOP in Python Eng. Omar Yahya
7
OOP in Python Eng. Omar Yahya
Code Description:
Base class (Shape):
Contains a draw method that does nothing but raise a NotImplementedError. This means that
each subclass must redefine this function.
Subclasses (Circle, Rectangle, Square):
Each subclass redefines a draw method to perform the appropriate shape drawing operation.
Draw_shape function:
This method accepts an object of type Shape or any of its subclasses, and calls the draw method
for that object.
Creating objects and calling methods:
Objects from the Circle, Rectangle, Square classes are created, and then passed to the
draw_shape method, which calls the appropriate draw method based on the type of the object.
With this example, you can see how polymorphism is used in object-oriented programming to
achieve different behaviors using the same interface.
print(result)