我用python编写了一个类class Vector(object):
def __init__(self, coordinates):
try:
if not coordinates:
raise ValueError
self.coordinates = tuple(coordinates)
self.dimension = len(coordinates)
except ValueError:
raise ValueError('The coordinates must be nonempty')
except TypeError:
raise TypeError('The coordinates must be an iterable')
def __add__(self,v):
v1 = np.array(self.coordinates)
v2 = np.array(v.coordinates)
result = v1 + v2
return result.tolist()
def __sub__(self, other):
v1 = np.array(self.coordinates)
v2 = np.array(other.coordinates)
result = v1 - v2
return result.tolist()
def __mul__(self, other):
return other * np.array(self.coordinates)
def multiply(self,other):
v = Decimal(str(other)) * np.array(self.coordinates)
return v
def __str__(self):
return 'Vector: {}'.format(self.coordinates)
def __eq__(self, v):
return self.coordinates == v.coordinates
我想重写操作*,这样可以实现如下功能:
^{pr2}$
所以我试过这样的代码:def __mul__(self, other):
return other * np.array(self.coordinates)
但是,我很失望地注意到这个函数只在Vector([1,2,3])*3
如果我写下:3*Vector([1,2,3])
上面写着:TypeError: unsupported operand type(s) for *: 'int' and 'Vector'
我怎样才能得到同时在3*Vector([1,2,3])和Vector([1,2,3])*3上工作的函数?在
非常感谢你。在