4

I am new to python OOP programming. I was doing this tutorial on overloading operators from here(Scroll down to operator Overloading). I couldn't quite understand this piece of code. I hope somebody will explain this in detail. To be precise I didn't understand the how are 2 objects being added here and what are the lines

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) 

doing here?


#!/usr/bin/python

class Vector:
   def __init__(self, a, b):
      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

This generates an output Vector(7,8). How are the objects v1 and v2 being added here?

2
  • 2
    Special Method Names Commented Mar 24, 2017 at 18:27
  • 2
    In situations like these, it's always good to step through code, line by line, in the debugger. It brings to light so much more information than you thought. It basically will walk you through what each operation is doing. Commented Mar 24, 2017 at 18:28

3 Answers 3

5

v1 + v2 is treated as a call to v1.__add__(v2), with self == v1 and other == v2.

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

Comments

2

This is the Python data model and your question is answered here

Basically when v1 + v2 is performed python internally performs v1.__add__(v2)

Comments

2

This code is performing vector addition, the same way you would add two vectors on paper, it combines the corresponding components using scalar addition. You are overriding the __add__ method to tell the interpreter how addition should be performed for your class.

The code:

self.a + other.a

combines the a component of your vector class. The code:

self.b + other.b

combines the b component of your vector class using the appropriate addition function for the type of b.

Those new component values are passed to the constructor of the Vector class to return a new Vector.

The + operator will invoke the __add__ method on your class to perform the addition.

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.