为什么我们需要 return 在 __add__ 函数中指向对象而不只是 returning x 和 y?

Why do we need to return Point object in __add__ function instead of just returning x and y?

我正在研究 Python 中的运算符重载并遇到了这段代码。我不清楚,为什么我们在 add 函数中 return Point(x,y) 而不是 returning x 和 y.

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) // here if we remove Point object and use return(x,y) it does not cause any errors
        
        
p1 = Point(1,5)  
p2 = Point(2,5)

print(p1 + p2)

(x,y) 语法创建元组对象,而 Point(x,y) 创建 Point class 的实例并设置其 x 和 y 属性。

这两种类型的 python 对象之间存在差异。元组是一个序列类型的对象,它是一个值列表的形式。元组本身只有两个值,以及适用于该类型集合的方法。您可以在此处阅读有关元组的更多信息:https://docs.python.org/3.3/library/stdtypes.html?highlight=tuple#tuple

另一方面,虽然您的点 class 仍然非常简单,但可以通过其他方法获得更多附加功能。例如,元组可能没有您在点 class 中创建的 add() 方法,或者它可能有另一个 add() 方法做其他事情。希望这能解决这个问题。