I'm learning Python overloading operation. I'm overloading the __add__ operation in class. why should i have to return in the form of object at the end to overloading function. The code is given below
class point:
def __init__(self,x,y):
self.x = x
self.y =y
def __add__(self,other):
x = self.x + other.x
y = self.y +other.y
return point(x,y)
def __str__(self):
return "({0},{1})".format(self.x,self.y)
point1 = point(1,2)
point2 = point(1,2)
print(point1+point2)
Another code for the same
class point:
def __init__(self,x,y):
self.x = x
self.y =y
def __add__(self,other):
x = self.x + other.x
y = self.y +other.y
return (x,y)
point1 = point(1,2)
point2 = point(1,2)
print(point1+point2)
Both the above code gives the same result. I don't understand why 'return point(x,y)' is used in first example
point1+point2to be atupleor apoint? Either one is valid. The question is what do you want to do with the result?xandyin class's instance variable than you don't need to return it. It will always available in all the methods or through the objectpointtogether, I would (99% of the time) expect to receive anotherpointobject as the output.