【发布时间】:2018-12-08 17:12:57
【问题描述】:
我这样用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
我想覆盖操作*,所以我可以实现如下功能:
3*Vector([1,2,3])=Vector([3,6,9])
所以我尝试了这样的代码:
def __mul__(self, other):
return other * np.array(self.coordinates)
但是,我很失望地发现此功能仅在以下情况下才有效
Vector([1,2,3])*3
如果我写了:
3*Vector([1,2,3])
上面写着:
TypeError: *: 'int' 和 'Vector' 的操作数类型不受支持
我怎样才能获得同时适用于3*Vector([1,2,3]) 和Vector([1,2,3])*3 的函数?
非常感谢。
【问题讨论】:
-
你需要定义
__rmul__
标签: python overwrite operation