I'd like to suggest some improvements to Yoriz's solution to make it more Pythonic, using
__iadd__
class Point(object):
def __init__(self, x, y):
self.x = x
self.y = y
def __repr__(self):
return 'Point> x: {}, y: {}'.format(self.x, self.y)
def __add__(self, other):
return Point(self.x + other.x, self.y + other.y)
def __iadd__(self, other):
self.x += other.x
self.y += other.y
return self
objectA = Point(3,5)
objectB = Point(7,5)
print(objectA)
print(objectA + objectB)
print(objectA)
objectA += objectB
print(objectA)
Output:
Point> x: 3, y: 5
Point> x: 10, y: 10
Point> x: 3, y: 5
Point> x: 10, y: 10
When I see the plus (+) operator (without it being in +=) I don't expect a side effect. I would not expect one. So I have __add__ instead return a new value. If we really want to modify a Point (which arguably, shouldn't be done) then Python gives you += for free, as it will do the regular plus then replace the left hand side with that new object. __iadd__ is simply more efficient, if you want to make it that way.
As an aside - I believe immutability is a wonderful thing, and I might even use __iadd__ in this case to throw an exception to enforce it. Immutable code is
much more easily reasoned about, since one need not worry about side effects, just read through straightforward code. (Note: in this case, creating a new point is cheap enough and += clear enough that the negatives to throwing an exception probably aren't worth it in practice even if the principal holds.)