Class Python3运算符重载

Class Python3运算符重载,class,python-3.x,operator-overloading,Class,Python 3.x,Operator Overloading,当涉及到我的类点时,我试图定义操作符类型add。点正是它看起来的(x,y)。但我似乎无法让操作员工作,因为代码一直在打印数据。我对这件事很陌生,有人能解释一下我做错了什么吗?谢谢这是我的密码: class Point: def __init__(self, x=0, y=0): self.x = x self.y = y def __add__(self, other): return Point(self.x + other.x, self.y + other.y) p

当涉及到我的类点时,我试图定义操作符类型add。点正是它看起来的(x,y)。但我似乎无法让操作员工作,因为代码一直在打印数据。我对这件事很陌生,有人能解释一下我做错了什么吗?谢谢这是我的密码:

class Point:
def __init__(self, x=0, y=0):
    self.x = x
    self.y = y
def __add__(self, other):
    return Point(self.x + other.x, self.y + other.y)
p1 = Point(3,4)
p2 = Point(5,6)
p3 = p1 + p2
print(p3)

“添加”功能正在按预期工作。问题出在你的
打印上。你得到了一个丑陋的结果,比如
,因为你没有告诉类你希望它如何显示自己。实现或使其显示一个漂亮的字符串

class Point:
    def __init__(self, x=0, y=0):
        self.x = x
        self.y = y
    def __add__(self, other):
        return Point(self.x + other.x, self.y + other.y)
    def __repr__(self):
        return "Point({}, {})".format(self.x, self.y)
p1 = Point(3,4)
p2 = Point(5,6)
p3 = p1 + p2
print(p3)
结果:

Point(8, 10)
“代码将继续打印
”。听起来很正常。你希望它打印什么?