Reputation: 189
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
Upvotes: 2
Views: 1457
Reputation: 1123790
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.
Upvotes: 1
Reputation: 3887
Yes, this is equivalent to:
result = first.__add__(second)
so:
self
is first
other
is second
result
is the new Vector2D
Upvotes: 3
Reputation: 81654
the argument
other
refers tosecond
, right?
Correct. You can verify that with a print
inside __add__
:
class Vector2D:
def __init__(self, x, y):
self.x = x
self.y = y
def __add__(self, other):
print(other.x, other.y)
return Vector2D(self.x + other.x, self.y + other.y)
first = Vector2D(5, 7)
second = Vector2D(3, 9)
result = first + second
>> 3 9
Upvotes: 1