Python OOP Programming

I am new to OOP programming in Python. I did this tutorial on operator overloading from here (scroll down to operator overload). I could not understand this piece of code. Hope someone explains this in detail. To be precise, I did not understand how 2 objects are added here and what are the strings

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) 

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 objects v1 and v2 added here?

+4
source share
3 answers

v1 + v2seen as a challenge v1.__add__(v2), with self == v1and other == v2.

+5
source

This is a Python data model, answers your question here

, v1 + v2, python v1.__add__(v2)

+2

, , , . __add__, .

:

self.a + other.a

. :

self.b + other.b

b b.

Vector .

+ __add__ .

+2

Source: https://habr.com/ru/post/1673155/


All Articles