user131983
user131983

Reputation: 3937

Query about Operator Overloading in Python

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

Upvotes: 0

Views: 37

Answers (1)

NPE
NPE

Reputation: 500893

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.

Upvotes: 3

Related Questions