Python TypeError:*:'Vector2'和'int'的不支持的操作数类型

时间:2011-01-11 06:02:39

标签: python

我正在尝试创建一个Vector2类。 当我尝试输入

vec1 = Vector2()
vec2 = vec1 * 5

它给了我错误:

TypeError: unsupported operand type(s) for *: 'Vector2' and 'int'

我的运营商重载是否有问题?

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, other):
    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))

1 个答案:

答案 0 :(得分:4)

不是__mul__而不是__mull__吗?将__mull__替换为__mul__,然后重试。