Download as pdf or txt
Download as pdf or txt
You are on page 1of 24

Chapter 4

Polymorphism
Declaration
 These slides are made for UIT, BU students only. I am not
holding any copy write of it as I had collected these study
materials from different books and websites etc. I have not
mentioned those to avoid complexity.

9/8/2023 2:25 PM Dr. Dipankar Dutta, UIT, BU 1.2


Topics
 Concept of Polymorphism
 Different types of Polymorphism
 Advantages and limitations of it

9/8/2023 2:25 PM Dr. Dipankar Dutta, UIT, BU 1.3


Polymorphism
 Polymorphism defines the ability to take different forms. The
word polymorphism means having many forms.
 In programming, polymorphism means the same function name
(but different signatures) being used for different types.
# Python program to demonstrate in-built polymorphic functions

# len() being used for a string


print(len(“Burdwan"))

# len() being used for a list


print(len([10, 20, 30]))
 Output:
7
3

9/8/2023 2:25 PM Dr. Dipankar Dutta, UIT, BU 1.4


Polymorphism
 Python does not support traditional function overloading like
some other programming languages, such as C++ or Java,
where you can define multiple functions with the same name but
different parameter lists. In Python, a function is determined by
its name and the number of arguments it takes, so defining
multiple functions with the same name but different parameters
will result in the latest definition overwriting the previous ones.
 However, you can achieve a form of function overloading in Python
using default arguments and variable-length argument lists (args and
kwargs). Here's how you can simulate function overloading in Python:

9/8/2023 2:25 PM Dr. Dipankar Dutta, UIT, BU 1.5


Polymorphism
 Examples of user-defined polymorphic functions by using
default arguments
# A simple Python function to demonstrate
# Polymorphism

def add(x, y, z = 0):


return x + y + z

# Driver code
print(add(2, 3))
print(add(2, 3, 4))
 Output:
5
9

9/8/2023 2:25 PM Dr. Dipankar Dutta, UIT, BU 1.6


Polymorphism
 Examples of user-defined polymorphic functions by Using
Variable-Length Arguments (args and kwargs):
def my_function(*args):
if len(args) == 1: # Code for one argument
result = args[0]
elif len(args) == 2: # Code for two arguments
result = args[0] + args[1]
else:
raise TypeError("Unsupported number of arguments")
return result
# Call the function with one or two arguments
print(my_function(5)) # Output: 5
print(my_function(5, 3)) # Output: 8

9/8/2023 2:25 PM Dr. Dipankar Dutta, UIT, BU 1.7


Polymorphism
 Polymorphism with class methods:
The below code shows how Python can use two different class
types, in the same way. We create a for loop that iterates through a
tuple of objects. Then call the methods without being concerned
about which class type each object is. We assume that these
methods actually exist in each class.
class India():
def capital(self):
print("New Delhi is the capital of India.")

def language(self):
print("Hindi is the most widely spoken language of India.")

def type(self):
print("India is a developing country.")
9/8/2023 2:25 PM Dr. Dipankar Dutta, UIT, BU 1.8
Polymorphism
class USA():
def capital(self):
print("Washington, D.C. is the capital of USA.")

def language(self):
print("English is the primary language of USA.")

def type(self):
print("USA is a developed country.")

 class MyClass: implicitly inherits from the base class object.


 class MyClass(): explicitly inherits from an empty tuple ().

9/8/2023 2:25 PM Dr. Dipankar Dutta, UIT, BU 1.9


Polymorphism
obj_ind = India()
obj_usa = USA()
for country in (obj_ind, obj_usa):
country.capital()
country.language()
country.type()

9/8/2023 2:25 PM Dr. Dipankar Dutta, UIT, BU 1.10


Polymorphism
 Output:
New Delhi is the capital of India.
Hindi is the most widely spoken language of India.
India is a developing country.
Washington, D.C. is the capital of USA.
English is the primary language of USA.
USA is a developed country.

9/8/2023 2:25 PM Dr. Dipankar Dutta, UIT, BU 1.11


Polymorphism
 Polymorphism with Inheritance:
In Python, Polymorphism lets us define methods in the child class
that have the same name as the methods in the parent class. In
inheritance, the child class inherits the methods from the parent
class. However, it is possible to modify a method in a child class
that it has inherited from the parent class. This is particularly useful
in cases where the method inherited from the parent class doesn‟t
quite fit the child class. In such cases, we re-implement the method
in the child class. This process of re-implementing a method in the
child class is known as Method Overriding.

9/8/2023 2:25 PM Dr. Dipankar Dutta, UIT, BU 1.12


Polymorphism
class Bird:
def intro(self):
print("There are many types of birds.")

def flight(self):
print("Most of the birds can fly but some cannot.")

class sparrow(Bird):
def flight(self):
print("Sparrows can fly.")

class ostrich(Bird):
def flight(self):
print("Ostriches cannot fly.")

9/8/2023 2:25 PM Dr. Dipankar Dutta, UIT, BU 1.13


Polymorphism
obj_bird = Bird()
obj_spr = sparrow()
obj_ost = ostrich()

obj_bird.intro()
obj_bird.flight()

obj_spr.intro()
obj_spr.flight()

obj_ost.intro()
obj_ost.flight()

9/8/2023 2:25 PM Dr. Dipankar Dutta, UIT, BU 1.14


Polymorphism
 Output:
There are many types of birds.
Most of the birds can fly but some cannot.
There are many types of birds.
Sparrows can fly.
There are many types of birds.
Ostriches cannot fly.

9/8/2023 2:25 PM Dr. Dipankar Dutta, UIT, BU 1.15


Polymorphism
 Polymorphism with a Function and objects:
It is also possible to create a function that can take any object,
allowing for polymorphism. In this example, let‟s create a function
called “func()” which will take an object which we will name “obj”.
Though we are using the name „obj‟, any instantiated object will be
able to be called into this function. Next, let‟s give the function
something to do that uses the „obj‟ object we passed to it. In this
case, let‟s call the three methods, viz., capital(), language() and
type(), each of which is defined in the two classes „India‟ and „USA‟.
Next, let‟s create instantiations of both the „India‟ and „USA‟ classes
if we don‟t have them already. With those, we can call their action
using the same func() function:

9/8/2023 2:25 PM Dr. Dipankar Dutta, UIT, BU 1.16


Polymorphism
class India():
def capital(self):
print("New Delhi is the capital of India.")

def language(self):
print("Hindi is the most widely spoken language of India.")

def type(self):
print("India is a developing country.")

9/8/2023 2:25 PM Dr. Dipankar Dutta, UIT, BU 1.17


Polymorphism

class USA():
def capital(self):
print("Washington, D.C. is the capital of USA.")

def language(self):
print("English is the primary language of USA.")

def type(self):
print("USA is a developed country.")

9/8/2023 2:25 PM Dr. Dipankar Dutta, UIT, BU 1.18


Polymorphism

def func(obj):
obj.capital()
obj.language()
obj.type()

obj_ind = India()
obj_usa = USA()

func(obj_ind)
func(obj_usa)

9/8/2023 2:25 PM Dr. Dipankar Dutta, UIT, BU 1.19


Polymorphism

 Output:
New Delhi is the capital of India.
Hindi is the most widely spoken language of India.
India is a developing country.
Washington, D.C. is the capital of USA.
English is the primary language of USA.
USA is a developed country.

9/8/2023 2:25 PM Dr. Dipankar Dutta, UIT, BU 1.20


Polymorphism

 Output:
New Delhi is the capital of India.
Hindi is the most widely spoken language of India.
India is a developing country.
Washington, D.C. is the capital of USA.
English is the primary language of USA.
USA is a developed country.

9/8/2023 2:25 PM Dr. Dipankar Dutta, UIT, BU 1.21


Advantages of Polymorphism

 It helps the programmer to reuse the codes, i.e., classes once written,
tested and implemented can be reused in the program where ever
required, which saves a lot of time.
 Single variable can be used to store multiple data types.
 Easy to debug the codes.
 Method overloading can be extended to builders that allow multiple
ways of initializing class objects. It helps you to identify several builders
for managing various forms of initializations.
 Method overriding functions along with inheritance without the need for
re-compilation to allow code reuse of existing groups.

9/8/2023 2:25 PM Dr. Dipankar Dutta, UIT, BU 1.22


Disadvantages of Polymorphism

 One of the main disadvantages of polymorphism is that developers find


it difficult to implement polymorphism in codes.
 Run time polymorphism can lead to the performance issue where
machine needs to decide which method or variable to invoke so it
basically degrades the performances as decisions are taken at run time.
 Polymorphism reduces the readability of the program. One needs to
identify the runtime behavior of the program to identify actual execution
time.
 The readability of the program is diminished by polymorphism. In order
to define real execution time, one has to recognize the program‟s
runtime actions.

9/8/2023 2:25 PM Dr. Dipankar Dutta, UIT, BU 1.23


End of Chapter 4

Questions?

You might also like