Python 中的魔术方法(四)数学运算方法, __add__(+), __or__(|)等方法

和比较运算符一样, 也可以通过魔术方法自定义 数字运算符的行为, 

1. 一元运算符

方法说明运算符
__pos__(self)实现取正的行为+obj
__neg__(self)实现取负的行为-obj
__abs__(self) 实现内置 abs() 函数的行为abs(obj)
__invert__(self)实现 ~ 运算符实现反转行为~(obj)
__round__(self, n)实现内置 round() 函数的行为round(obj, n)
__floor__(self)

实现 math.floor() 的行为,

向下四舍五入到最接近的整数

math.floor(obj)
__ceil__(self)

实现 math.ceil() 的行为,

向上四舍五入到最接近的整数

math.ceil(obj)
__trunc__(self)

实现 math.trunc() 的行为

截断为积分

math.trunc(obj)

2. 普通算数运算符

方法说明运算符
__add__(self, other)加法+
__sub__(self, other)减法-
__mul__(self, other)乘法*
__div__(self, other)除法/
__floordiv__(self, other)整数除法//
__mod__(self, other)取余数%
__divmod__(self, other)使用 divmod() 内置函数实现长除法行为divmod(a, b)
__pow__(self, other)

指数运算

 ** 
__lshift__(self, other)

位运算 左移 

<<
__rshift__(self, other)位运算 右移 >>
__and__(self, other)位运算,并&
__or__(self, other)位运算,或|
__xor__(self, other)位运算,异或^

3. 反向算数运算符

这个名字优点奇怪, 其实就是运算符定义了   obj  +   other 时的实现。 反向运算符定义了 other + obj 时的实现。 即 被加 被除时的实现。 大部分情况下,他们是一回事, 但是某些场景需要区分, 比如除法时, 除对方要求对方不能为0, 而被除则要求自己的值不能为0.

方法说明运算符
__radd__(self, other)加法+
__rsub__(self, other)减法-
__rmul__(self, other)乘法*
__rdiv__(self, other)除法/
__rfloordiv__(self, other)整数除法//
__rmod__(self, other)取余数%
__rdivmod__(self, other)使用 divmod() 内置函数实现长除法行为divmod(a, b)
__rpow__(self, other)

指数运算

 ** 
__rlshift__(self, other)

位运算 左移 

<<
__rshift__(self, other)位运算 右移 >>
__rand__(self, other)位运算,并&
__ror__(self, other)位运算,或|
__rxor__(self, other)位运算,异或^

 4. 自增运算符

实现 += -=等自增运算的魔术方法

方法说明运算符
__iadd__(self, other)加法+=
__isub__(self, other)减法-=
__imul__(self, other)乘法*=
__idiv__(self, other)除法/=
__ifloordiv__(self, other)整数除法//=
__imod__(self, other)取余数%=
__idivmod__(self, other)使用 divmod() 内置函数实现长除法行为divmod(a, b)
__ipow__(self, other)

指数运算

 **=
__ilshift__(self, other)

位运算 左移 

<<=
__ishift__(self, other)位运算 右移 >>=
__iand__(self, other)位运算,并&=
__ior__(self, other)位运算,或|=
__ixor__(self, other)位运算,异或^=

5. 类型转换

实现诸如 float(), str() 等内置类型转换函数的行为的魔术方法

方法说明运算符
__int__(self)int 的类型转换int
__long__(self)long 的类型转换 Python3.x 版本已删除long
__float__(self)float 的类型转换float
__complex__(self)复数类型转换complex
__oct__(self)8 进制类型转换oct
__hex__(self)16 进制类型转换hex
__index__(self)当在切片表达式中使用对象时,实现到 int 的类型转换。如果您定义可能用于切片的自定义数字类型,则应定义 __index__ . obj.index()
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值