【发布时间】:2020-11-18 18:27:12
【问题描述】:
所以我写了一个愚蠢的示例类:
class Pair:
def __init__(self, x, y):
self._x = x
self._y = y
# add two objects of type Paar
def __add__(self, other):
new_x = self._x + other._x
new_y = self._y + other._y
# better this?
self._x = new_x
self._y = new_y
return self
# or this?
# return Paar(new_x, new_y)
现在我想添加这个类的两个实例,我只是有点卡在我的脑海里。这两个选项中的哪一个更适合使用?
【问题讨论】:
-
你的实现
returns self不好(至少,它违反约定),__add__挂钩到+,通常应该不改变它的参数.为此,请使用与+=挂钩的__iadd__。所以你只需要return Paar(new_x, new_y) -
非常感谢!这澄清了很多:)
标签: python class operator-overloading