Operator overloading

 

Operator overloading

The operator is used for basic purpose. It can work well with inbuilt datatype. Following example suggest the + operator add two numeric value and concate two strings and lists. To make to the operator capable so that it can work with user defined data type (class) too. To make operator powerful it is overloaded.

So operator overloading means enhance the meaning of operator overloading.

Example:

x=5

y=10

z=x+y

print("The value of z is",z)


x="abc"

y="def"

z=x+y

print("The value of z is",z)


x=[1,2,3]

y=[4,5,6]

z=x+y

print(z)

Output:

The value of z is 15

The value of z is abcdef

[1, 2, 3, 4, 5, 6]

Above example suggest that python support operator overloading. The + operator add two integer value and concate two strings.

Following example suggest how operator can be overloaded. To overload different operators there are in built method available.

operator overloading methods:

+ object__add__(self,other)

- object__sub__(self,other)

* object__mul__(self,other)

/ object__div__(self,other)

% object__mod__(self,other)

> object__gt__(self,other)

< object__lt__(self,other)

Example:

class Rupees:

def __init__(self,r):

self.r=r

def __add__(self,other):

rtop=self.r*100

return rtop+other.p


class Paise:

def __init__(self,p):

self.p=p


r1=Rupees(5)

p1=Paise(50)


print("Total amount is ", r1+p1 ,"paise" )

Output:

Total amount is 550 paise