和比较运算符一样, 也可以通过魔术方法自定义 数字运算符的行为,
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() |