python中参数的顺序_Python中的运算符重载:处理不同类型和参数顺序

I have a simple class that helps with mathematical operations on vectors (i.e. lists of numbers). My Vector can be multiplied by other instances of Vector or a scalar (float or int).

In other, more strongly typed, languages I would create a method to multiply two vectors and a separate method to multiply a vector by and int/float. I'm still pretty new to Python and am not sure how I would implement this. The only way I can think of doing it is override __mul__() and test the incoming parameter:

class Vector(object):

...

def __mul__(self, rhs):

if isinstance(rhs, Vector):

...

if isinstance(rhs, int) or isinstance(rhs, float):

...

Even if I do it that way I would be forced to multiply a Vector by a scalar like this:

v = Vector([1,2,3])

result = v * 7

What if I wanted to reverse the order of the operands in the multiplication?

result = 7 * v

What is the right way to do that in Python?

解决方案

You also need to implement __rmul__. When the initial call to int.__mul__(7, v) fails, Python will next try type(v).__rmul__(v, 7).

def __rmul__(self, lhs):

return self * lhs # Effectively, turn 7 * v into v * 7

As Rawing points out, you could simply write __rmul__ = __mul__ for this definition. __rmul__ exists to allow for non-commutative multiplication where simply deferring to __mul__ with the operands reversed isn't sufficient.

For instance, if you were writing a Matrix class and wanted to support multiplication by a nested list, e.g.,

m = Matrix(...) # Some 2 x 2 matrix

n = [[1, 2], [3,4]]

p = n * m

Here, the list class wouldn't know how to multiple a list by a Matrix instance, so when list.__mul__(n, m) fails, Python would next try Matrix.__rmul__(m, n). However, n * m and m * n are two different results in general, so Matrix.__rmul__(m, n) != Matrix.__mul__(m, n); __rmul__ has to do a little extra work to generate the right answer.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值