[英]How to properly overwrite __add__ method and create new object in Python?
所以我寫了一個愚蠢的示例類:
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)
現在我想添加這個類的兩個實例,我只是有點卡在我的腦海里。 這兩個選項中的哪一個是首選?
第一個解決方案是第二個(評論)解決方案。 在第二個中,您返回該類的一個新實例,而在第一個中,您修改了第一個實例,這不是預期的行為。 為了說明這個問題:
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.