python mul函数_我如何在python中重写\uuu mul_uu函数

我用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上工作的函数?在

非常感谢你。在

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值