OOP in Python Eng.
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.
Figure 2: Types of polymorphism.
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
Types of Polymorphism in OOP in Python:
• Method Overriding (Runtime Polymorphism): Method overriding is a form of runtime
polymorphism where a subclass provides a specific implementation of a method that is
already defined in its superclass. The method in the subclass overrides the method in the
superclass, allowing objects of the subclass to use the overridden method instead of the one
in the superclass.
• Duck Typing: Duck typing is a type of polymorphism that is determined by the presence
of certain methods and properties rather than the object's actual type. The term comes from
the phrase "If it looks like a duck, swims like a duck, and quacks like a duck, then it
probably is a duck." In Python, this means that if an object implements the required
method(s), it can be used in place of any other object, regardless of its class.
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.
Polymorphism in addition operator
We know that the + operator is used extensively in Python programs. But it does not have a single
usage.
For integer data types, + operator is used to perform arithmetic addition operation.
Example 1: Polymorphism in + (plus) operator
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.
Function Polymorphism in Python
There are some functions in Python which are compatible to run with multiple data types.
One such function is the len() function. It can run with many data types in Python. Let's look at
some examples use cases of the function.
Example 2: Polymorphic len() function
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.
Figure 3: Polymorphism in built-in function.
Polymorphism in Class Methods (Duck typing)
We can then later generalize calling these methods by disregarding the object we are working with.
Let's look at an example:
4
OOP in Python Eng. Omar Yahya
Example 3: Polymorphism in Class Methods
class Duck:
def quack(self):
print("Quack!")
class Person:
def quack(self):
print("I can't quack like a duck, but I can try!")
# Function that expects an object that can quack
def make_quack(obj):
obj.quack()
# Creating instances of different classes
duck = Duck()
person = Person()
# Calling the function with different objects
make_quack(duck) # Output: Quack!
make_quack(person) # Output: I can't quack like a duck, but I
can try!
In this example, the make_quack() method expects an object with a quack() method. Both the
Duck and Person classes implement a quack method(), demonstrating duck typing in action.
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.
Polymorphism and Inheritance
Like in other programming languages, the child classes in Python also inherit methods and
attributes from the parent class. We can redefine certain methods and attributes specifically to fit
the child class, which is known as Method Overriding.
Method Overriding:
• Occurs when a derived class defines a method with the same name and signature as a
method in its base class.
• The derived class's method overrides the base class's method, allowing for specific
behavior customization.
• When you call the method on an object of the derived class, the derived class's version is
executed.
Polymorphism allows us to access these overridden methods and attributes that have the same
name as the parent class.
Figure 4: Polymorphism in inheritance.
6
OOP in Python Eng. Omar Yahya
Let's look at an example:
Example 4: Method Overriding
# Define base class
class Shape:
def draw(self):
raise NotImplementedError("Subclass must implement
abstract method")
# Define Circle class
class Circle(Shape):
def draw(self):
return "Drawing a Circle"
# Define Rectangle class
class Rectangle(Shape):
def draw(self):
return "Drawing a Rectangle"
# Define Square class
class Square(Shape):
def draw(self):
return "Drawing a Square"
# Method to accept and draw any shape
def draw_shape(shape):
print(shape.draw())
# Create objects from different classes
circle = Circle()
rectangle = Rectangle()
square = Square()
# Using the draw_shape method with different objects
draw_shape(circle) # Output: "Drawing a Circle"
draw_shape(rectangle) # Output: "Drawing a Rectangle"
7
OOP in Python Eng. Omar Yahya
draw_shape(square) # Output: "Drawing a Square"
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.
Example of Function Overloading
In Python, compile-time polymorphism is primarily achieved through function overloading,
although Python does not support true function overloading. However, you can define functions
with the same name in Python, but only the latest defined function will be considered.
def add(a, b, c):
return a + b + c
def add(a, b):
return a + b
result = add(2, 3) # Error: Only the latest defined function
is available
print(result)