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))
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.