Ruthvik Vaila
Ruthvik Vaila

Reputation: 537

Python OOP Programming

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?

Upvotes: 4

Views: 417

Answers (3)

Tague Griffith
Tague Griffith

Reputation: 4173

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.

Upvotes: 2

xssChauhan
xssChauhan

Reputation: 2838

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

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

Upvotes: 2

chepner
chepner

Reputation: 530960

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

Upvotes: 5

Related Questions