Pract14
Pract14
Overloading:
class Student:
def hello(self, name=None):
if name is not None:
print('Hey ' + name)
else:
print('Hey ')
# Creating a class instance
std = Student()
# Call the method
std.hello()
# Call the method and pass a parameter
std.hello('Prasad')
Output:
Overridding:
1|Page
Subject: PWP[22616]
Practical No.14:Demonstrate overloading and Overridding.
Name: Ritesh Doibale Roll no:41
Practical related questions:
Q2.
# parent class
class Animal:
multicellular = True
eukaryotic = True
# function breath
def breathe(self):
print("I breathe oxygen.")
# function feed
def feed(self):
print("I eat food.")
# child class
class Herbivorous(Animal):
# function feed
def feed(self):
print("I eat only plants. I am vegetarian.")
herbi = Herbivorous()
herbi.feed()
# calling some other function
herbi.breathe()
Output:
2|Page
Subject: PWP[22616]
Practical No.14:Demonstrate overloading and Overridding.
Name: Ritesh Doibale Roll no:41
x.Exercise:
Q1. Write a Python program to create a class to print an integer and a character with two methods
having the same name but different sequence of the integer and the character parameters. For
example, if the parameters of the first method are of the form (int n, char c), then that of the second
method will be of the form (char c, int n)
class Print:
def print_ic(self, n, c):
print(n, c)
Q2. Write a Python program to create a class to print the area of a square and a rectangle. The class
has two methods with the same name but different number of parameters. The method for printing
area of rectangle has two parameters which are length and breadth respectively while the other
method for printing area of square has one parameter which is side of square.
class Area:
def print_area(self, length=None, breadth=None, side=None):
if length is not None and breadth is not None:
self.length = length
self.breadth = breadth
print("Area of rectangle is: ", self.length * self.breadth)
elif side is not None:
self.side = side
print("Area of square is: ", self.side ** 2)
else:
print("Invalid number of parameters")
obj = Area()
obj.print_area(10, 5)
obj.print_area(5)
Output:
3|Page
Subject: PWP[22616]
Practical No.14:Demonstrate overloading and Overridding.
Name: Ritesh Doibale Roll no:41
Q3. Write a Python program to create a class 'Degree' having a method 'getDegree' that prints "I got a
degree". It has two subclasses namely 'Undergraduate' and 'Postgraduate' each having a method with
the same name that prints "I am an Undergraduate" and "I am a Postgraduate" respectively. Call the
method by creating an object of each of the three classes.
class Degree:
def getDegree(self):
print("I got a degree")
class Undergraduate(Degree):
def getDegree(self):
print("I am an Undergraduate")
class Postgraduate(Degree):
def getDegree(self):
print("I am a Postgraduate")
obj1 = Degree()
obj2 = Undergraduate()
obj3 = Postgraduate()
obj1.getDegree()
obj2.getDegree()
obj3.getDegree()
Output:
4|Page