I'm having trouble understanding how the self-reference for this class works in this code:
class Vector2D:
def __init__(self, x, y):
self.x = x
self.y = y
def __add__(self, other):
return Vector2D(self.x + other.x, self.y + other.y)
first = Vector2D(5, 7)
second = Vector2D(3, 9)
result = first + second
print(result.x)
print(result.y)
--
Just to check if I'm understanding how magic methods work, in result = first + second
, the argument other
refers to second
right?
--Edit:
Thanks, I guess that clears up my confusions regarding other
.
I still don't get how this line works though: return Vector2D(self.x + other.x, self.y + other.y)
i.e. the class Vector2D
being referenced inside it
Yes, other
is the right-hand-side expression result, second
in your case.
From the object.__add__()
documentation:
For instance, to evaluate the expression
x + y
, wherex
is an instance of a class that has an__add__()
method,x.__add__(y)
is called.
The expression Vector2D(self.x + other.x, self.y + other.y)
creates a new instance of the class with new values for x
and y
, which here are constructed from the sum of the current instance x
and y
and the same attributes on the right-hand side instance.
A new instance is created because the normal semantics of +
are to return a new instance, leaving the operands themselves untouched. Compare this to adding up two lists (['foo', 'bar'] + ['bar', 'baz']
); there too a new list object is returned.