0

I don't understand how the + Operator between v1 and v2 results in the calling of the function add in the code below.

self.a = a
self.b = b

def __str__(self):
   return 'Vector (%d, %d)' % (self.a, self.b)

def __add__(self,other):
   return Vector(self.a + other.a, self.b + other.b)

v1 = Vector(2,10)
v2 = Vector(5,-2)

print v1 + v2

Thanks

1 Answer 1

3

When the interpreter sees that you're trying to add something to a Vector object, it checks whether the object has a method called __add__(). If it does, the interpreter calls that method, passing both operands. The return value of the method is the result of the operation.

For each operator that can be overloaded there is a magic method that can be implemented to perform the operation.

This explanation is simplified in the sense that it is also possible for the right-hand operand (v2 in your example) to overload the operation. There are also special rules around in-place operator such as +=, and other complications.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.