Python实现类似数值对象的方式

参考资料
https://docs.python.org/2/reference/datamodel.html#emulating-numeric-types

在Python中,可以通过定义以下方法来模拟数字对象。与未实现的特定数字类型不支持的操作相对应的方法应保持未定义(例如,非整数的按位操作)。

方法含义备注
object.add(self, other)+
object.sub(self, other)-
object.mul(self, other)*
object.floordiv(self, other)//
object.mod(self, other)%
object.divmod(self, other)divmod()相当于使用__floordiv__()与__mod__()
object.pow(self, other[, modulo])pow()或**
object.lshift(self, other)<<
object.rshift(self, other)>>
object.and(self, other)&
object.xor(self, other)^
object.or(self, other)|
object.div(self, other)/在__future__.division无效时被使用
object.truediv(self, other)/在__future__.division有效时被使用
如果一个方法不支持对提供的参数进行操作,则应返回NotImplemented。
object.radd(self, other)+使用了反射
object.rsub(self, other)-使用了反射
object.rmul(self, other)*使用了反射
object.rdiv(self, other)/使用了反射
object.rtruediv(self, other)/使用了反射
object.rfloordiv(self, other)//使用了反射
object.rmod(self, other)%使用了反射
object.rdivmod(self, other)divmod()使用了反射
object.rpow(self, other)pow()或**使用了反射
object.rlshift(self, other)<<使用了反射
object.rrshift(self, other)>>使用了反射
object.rand(self, other)&使用了反射
object.rxor(self, other)^使用了反射
object.ror(self, other)|使用了反射
object.iadd(self, other)+=
object.isub(self, other)-=
object.imul(self, other)*=
object.idiv(self, other)/=
object.itruediv(self, other)/=
object.ifloordiv(self, other)//=
object.imod(self, other)%=
object.ipow(self, other[, modulo])**=
object.ilshift(self, other)<<=
object.irshift(self, other)>>=
object.iand(self, other)&=
object.ixor(self, other)^=
object.ior(self, other)|=
object.neg(self)-负数符号、取反
object.pos(self)+正数符号
object.abs(self)abs()取绝对值
object.invert(self)~二进制取反
object.complex(self)complex()
object.int(self)int()
object.long(self)long()
object.float(self)float()
object.oct(self)oct()
object.hex(self)hex()
object.index(self)operator.index()
object.coerce(self, other)mixed-mode
  • 如果只定义__truediv__()__div__()中的一种,则该对象将不支持上下文中的除法, 并抛出一个TypeError 。
  • 带有反射操作的方法仅当在左操作数不支持相应操作且操作数具有不同类型时才会被调用。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值