参考资料:
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 。- 带有反射操作的方法仅当在左操作数不支持相应操作且操作数具有不同类型时才会被调用。