On 20/06/17 23:39, Rex Florian via Tutor wrote: > 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): > def __str__(): > def __add__(self,other): > return Vector(self.a + other.a, self.b + other.b)
> print(v1 + v2 + v3) When you do the addition Python evaluates it from left to right so it is interpreted as: ((v1+v2) + v3) so Python does: v1.__add__(v2) Which returns a new vector, let's call it vt Python then does: vt.__add__(v3) which returns another new vector, lets call it result, which is what gets printed using print (result.__str__()) -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos _______________________________________________ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor