import math
class Vector2(object):
def __init__(self, x = 0.0, y = 0.0):
self.x = x
self.y = y
def __str__(self):
return "(%s, %s)" % (self.x, self.y)
@classmethod
def from_points(P1, P2):
return Vector2(P2[0] - P1[0], P2[1] - P1[1])
def get_magnitude(self):
return math.sqrt(self.x**2 + self.y**2)
def normalize(self):
magnitude = self.get_magnitude()
self.x /= magnitude
self.y /= magnitude
# rhs stands for Right Hand Side
def __add__(self, rhs):
return Vector2(self.x + rhs.x, self.y + rhs.y)
A = (10.0, 20.0)
B = (30.0, 35.0)
C = (15.0, 45.0)
AB = Vector2.from_points(A, B)
BC = Vector2.from_points(B, C)
AC = Vector2.from_points(A, C)
print "Vector AC is", AC
AC = AB + BC
print "AB + BC is ", AC
In the code above I'M getting an error at the from_points function. It telling that it need 2 arguments but I've given it three. I can't find a third. There was also a program similar to this one where the from_points function returned an extra argument in it parameter called cls, why doesn't this one need what?
One last thing, could someone please explain the __add__ constructor to me? Thanks.