Write a program in Python to demonstrate Method overloading and Method overriding
To overload a method in Python, we need to write the method logic in such a way that
depending upon the parameters passed, a different piece of code executes inside the
function. Take a look at the following example:
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
Hey
Hey Prasad
The method overriding in Python means creating two methods with the same name but
differ in the programming logic. The concept of Method overriding allows us to
change or override the Parent Class function in the Child Class.
Example
# Python Method Overriding
class Employee:
def message(self):
print('This message is from Employee Class')
class Department(Employee):
def message(self):
print('This Department class is inherited from Employee')
emp = Employee()
emp.message()
print('------------')
dept = Department()
dept.message()
Output
This message is from Employee Class
------------
This Department class is inherited from Employee
Example
class Display:
def printMsg(self,x,y):
if type(x)==int:
print("Interger MSg",x," ",y)
else:
print("Char MSg",x," ",y)
a=Display()
a.printMsg(51,"Yash")
a.printMsg("Yash",56)
class Degree :
def getDgree(self) :
print("I got a degree .")
class Undergraduate(Degree) :
def state(self) :
print("I am Underdraduate .")
class Postgraduate(Degree) :
def state(self) :
print("I am Postdraduate .")
obj1 = Degree()
obj2 = Undergraduate()
obj3 = Postgraduate()
obj1.getDgree()
obj2.getDgree()
obj2.state()
obj3.getDgree()
obj3.state()