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

__rmul__表示__mul__的反面

而__radd__表示__add__

。。。在

当左侧运算符为正常操作返回NotImplemented时调用这些函数(因此操作2 + vector_instance将首先尝试:(2).__add__(vector_instance),但如果返回{},则调用vector_instance.__radd__(2))。在

但是我不会在算术特殊方法中使用isinstance检查,这将导致大量代码重复。在

实际上,您可以在__init__中创建一个特殊情况,并在那里实现从标量到Vector的转换:class Vector(object):

def __init__(self, x, y=None, z=None):

if y is None and z is None:

if isinstance(x, Vector):

self.x, self.y, self.z = x.x, x.y, x.z

else:

self.x, self.y, self.z = x, x, x

elif y is None or z is None:

raise ValueError('Either x, y and z must be given or only x')

else:

self.x, self.y, self.z = x, y, z

def __mul__(self, other):

other = Vector(other)

return Vector(self.x*other.x, self.y*other.y, self.z*other.z)

__rmul__ = __mul__ # commutative operation

def __sub__(self, other):

other = Vector(other)

return Vector(self.x-other.x, self.y-other.y, self.z-other.z)

def __rsub__(self, other): # not commutative operation

other = Vector(other)

return other - self

def __repr__(self):

return 'Vector({self.x}, {self.y}, {self.z})'.format(self=self)

这应该如预期的那样工作:

^{pr2}$

请注意,这是一个快速而肮脏的草稿(可能有几个bug)。我只想介绍一个“总体思路”,如何在每个算术运算中不使用特殊的类型大小写来解决这个问题。在

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值