Function overloading in python by R4R Team

-Function overloading is a concept in which we have a multiple function of same name within the class.


program-

#create class
class A():
def add(self,x,y):
return x+y
def add(self,x,y,z):
return x+y+z

#create object
a=A()
print(a.add(1,2,3))
print(a.add(2,3))


output-

6
line 11, in
print(a.add(2,3))

TypeError: add() missing 1 required positional argument: 'z'


-In this program, we have a two function of same name 'add' so python select second add() function by default.
-In some other programming language like c++, this program will not give any kind of error and give the 6 and 5 as a output.

To overcome this error or achieve the function overloading -

program-

#create class
class A():
def add(self,x,y,z=0):
return x+y+z

#create object
a=A()
print(a.add(1,2,3))
print(a.add(2,3))


output-

6
5


-In this program, now we are able to add two number as well as three number




Leave a Comment:
Search
Categories
R4R Team
R4Rin Top Tutorials are Core Java,Hibernate ,Spring,Sturts.The content on R4R.in website is done by expert team not only with the help of books but along with the strong professional knowledge in all context like coding,designing, marketing,etc!