[英]How to properly overwrite __add__ method and create new object in Python?
So I wrote a stupid example class:所以我写了一个愚蠢的示例类:
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)
Now I want to add two instances of this class and I'm just a little stuck in my head.现在我想添加这个类的两个实例,我只是有点卡在我的脑海里。 Which of the two options would be the preferred one to use?
这两个选项中的哪一个是首选?
The first solution is the second(commented) one.第一个解决方案是第二个(评论)解决方案。 In the second one, you return a new instance of the class while in the first, you modify inplace the first instance, which is not the expected behaviour.
在第二个中,您返回该类的一个新实例,而在第一个中,您修改了第一个实例,这不是预期的行为。 To illustrate the issue:
为了说明这个问题:
class Pair_v1:
def __init__(self, x, y):
self._x = x
self._y = y
# add two objects of type Pair
def __add__(self, other):
new_x = self._x + other._x
new_y = self._y + other._y
return Pair_v1(new_x, new_y)
# Create two instances of Pair
pair1 = Pair_v1(2.0, 5.0)
pair2 = Pair_v1(7.0, 2.7)
# Add pair1 to pair2
pair1 += pair2
print('x = {}'.format(pair1._x))
print('y = {}'.format(pair1._y))
# Create a third instances as the sum of the two previous
pair3 = pair1 + pair2
print('In this case, pair1 IS NOT modified when creating pair3 (expected behavior).')
print('x = {}'.format(pair1._x))
print('y = {}'.format(pair1._y))
print('\n')
class Pair_v2:
def __init__(self, x, y):
self._x = x
self._y = y
# add two objects of type Pair
def __add__(self, other):
self._x += other._x
self._y += other._y
return self
# Create two instances of Pair
pair1 = Pair_v2(2.0, 5.0)
pair2 = Pair_v2(7.0, 2.7)
# Add pair1 to pair2
pair1 += pair2
print('x = {}'.format(pair1._x))
print('y = {}'.format(pair1._y))
# Create a third instances as the sum of the two previous
pair3 = pair1 + pair2
print('In this case, pair1 IS modified when creating pair3 (unexpected behavior)')
print('x = {}'.format(pair1._x))
print('y = {}'.format(pair1._y))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.