0

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

3
  • 2
    Do you want point1+point2 to be a tuple or a point? Either one is valid. The question is what do you want to do with the result? Commented Oct 25, 2019 at 12:46
  • Your code is not good. Please explain what you want to achieve? If you are saving the x and y in class's instance variable than you don't need to return it. It will always available in all the methods or through the object Commented Oct 25, 2019 at 12:51
  • If I add two objects of type point together, I would (99% of the time) expect to receive another point object as the output. Commented Oct 25, 2019 at 13:26

1 Answer 1

3

These are not the same, one returns an instance of the point class, another returns a tuple. What is printed is the same, due to how __str__ is defined for the point class.

You don't need to return another instance of the point class, but I can imagine there are use cases where this would be desired. Also, it's quite natural to assume that the group of instances of the point class is "closed" under addition, meaning that adding two instances of the class results in another instance of the class.

See what happens in such a case, when I want to get a point that results from adding two points. In case of returning return point(x,y), I can just assign the result of addition to some variable, e.g., point3 = point1 + point2. In case of return (x,y) I'd have to do something convoluted like point3 = point(*(point1 + point2)) or point3 = ((point1 + point2)[0], (point1 + point2)[1]).

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.