Operator overloading



Operator Overloading

When we add, subtract, divide, multiply two int or float objects using operators +,-,*,/,, the corresponding method  __add__, __sub__, __mul__, __div__ gets invoked for the class type of objects on which the operators is to be applied.Use of these syntactic operators for objects of different class(type) is called operator overloading.

For example:

class Point:
    def __init__(self, x=0, y=0):
        self.x = x
        self.y = y

    def __str__(self):
        return "({0},{1})".format(self.x, self.y)

    def __add__(self, other):
        x = self.x + other.x
        y = self.y + other.y
        return Point(x, y)


p1 = Point(1, 2)
p2 = Point(2, 3)

print(p1+p2)

 


Post a Comment

0 Comments