The concept of defining multiple methods with the same name, different
number of arguments within a same class is known as method overloading.
Note - Python doesn’t
support method overloading.
Example –
class A:
def m1(self,a):
print 'in one parameter m1 of A'
def m1(self,a,b):
print 'in two parameter m1 of A'
A1=A()
A1.m1(5,10)
A1.m1(5)
def m1(self,a):
print 'in one parameter m1 of A'
def m1(self,a,b):
print 'in two parameter m1 of A'
A1=A()
A1.m1(5,10)
A1.m1(5)
Output –
in two parameter m1 of A
Traceback (most recent call last):
File "C:/Users/om/PycharmProjects/Pythonn/if3.py", line 8, in <module>
A1.m1(5)
TypeError: m1() takes
exactly 3 arguments (2 given)
Example –
class A:
def m1(self,*args):
for p in args:
print p
A1=A()
A1.m1(10,20)
A1.m1(100,200,300)
A1.m1('rakesh','bamunimaidam','guwahati','assam')
def m1(self,*args):
for p in args:
print p
A1=A()
A1.m1(10,20)
A1.m1(100,200,300)
A1.m1('rakesh','bamunimaidam','guwahati','assam')
Output –
10
20
100
200
300
rakesh
bamunimaidam
guwahati
assam
Note - * is not method
overloading.
Example –
class A:
def add(self,instanceof,*args):
if instanceof == 'int':
result = 0
if instanceof == 'str':
result=' '
for i in args:
result = result+i
print result
A1=A()
A1.add('int',10,20,30)
A1.add('str','rakesh','kumar')
def add(self,instanceof,*args):
if instanceof == 'int':
result = 0
if instanceof == 'str':
result=' '
for i in args:
result = result+i
print result
A1=A()
A1.add('int',10,20,30)
A1.add('str','rakesh','kumar')
Output –
60
rakeshkumar
No comments:
Post a Comment