Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python OOP Programming

Tags:

python

oop

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?

like image 880
Ruthvik Vaila Avatar asked Jan 04 '23 07:01

Ruthvik Vaila


2 Answers

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

like image 131
chepner Avatar answered Jan 06 '23 22:01

chepner


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

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

like image 34
xssChauhan Avatar answered Jan 06 '23 22:01

xssChauhan