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 = xself.y = ydef __str__(self):return "({0},{1})".format(self.x, self.y)def __add__(self, other):x = self.x + other.xy = self.y + other.yreturn Point(x, y)p1 = Point(1, 2)p2 = Point(2, 3)print(p1+p2)
0 Comments
Doubts? Please let our team know So that we can serve you better.