[Tutor] Class
Rex Florian
sunnlotus at aol.com
Tue Jun 20 18:39:31 EDT 2017
Hello,
Below is a class I am using to comprehend how class works.
The code came from tutorialspoint.com and executes correctly but I do not understand why it works.
The original example defined just v1 and v2. I decided to experiment and instantiated v3.
The executed the print statement yields a correct answer which baffles me as to how.
I also tried (v1 + v2 + v3 + v1) which works as well.
Can someone explain how Python achieves the vector addition of more than 2 vectors
without some kind of looping?
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)
v3 = Vector(16,-14)
print(v1 + v2 + v3)
More information about the Tutor
mailing list