I am trying to create a Vector2 class. When I try to type
vec1 = Vector2()
vec2 = vec1 * 5
it gives me the error:
TypeError: unsupported operand type(s) for *: 'Vector2' and 'int'
Is there something wrong with my operator overloading?
class Vector2(object):
def __init__(self, x = 0.0, y = 0.0):
self.X = x
self.Y = y
def __add__(self, other):
if isinstance(other, Vector2):
new_vec = Vector2()
new_vec.X = self.X + other.X
new_vec.Y = self.X + other.Y
return new_vec
else:
raise TypeError("value must be a vector.")
def __radd__(self, other):
return self.__add__(other)
def __sub__(self, othe开发者_运维技巧r):
new_vec = Vector2()
new_vec.X = self.X - other.X
new_vec.Y = self.Y - other.Y
def __mull__(self, value):
new_vec = Vector2()
new_vec.X = self.X * value
new_vec.Y = self.Y * value
return new_vec
def __rmull__(self, value):
return self.__mull__(value)
def __div__(self, value):
new_vec = Vector2()
new_vec.X = self.X / value
new_vec.Y = self.Y / value
return new_vec
def dot(vector1, vector2):
return ((vector1.X * vector2.X) + (vector1.Y + vector2.Y))
Isn't it __mul__
and not __mull__
? Replace your __mull__
with __mul__
and try again.
精彩评论