内容来源于网络,本人只是在此稍作整理,如有涉及版权问题,归小甲鱼官方所有。
算数运算的魔法方法
- 反运算相关的魔法方法
魔法方法 | 定义 |
---|---|
__ radd__(self, other) | 定义加法的行为:+(当左操作数不支持相应的操作时被调用) |
__ rsub__(self, other) | 定义减法的行为:-(当左操作数不支持相应的操作时被调用) |
__ rmul__(self, other) | 定义乘法的行为:*(当左操作数不支持相应的操作时被调用) |
__ rtruediv__(self, other) | 定义真除法的行为:/(当左操作数不支持相应的操作时被调用) |
__ rfloordiv__(self, other) | 定义整数除法的行为://(当左操作数不支持相应的操作时被调用) |
__ rmod__(self, other) | 定义取模算法的行为:%(当左操作数不支持相应的操作时被调用) |
__ rdivmod__(self, other) | 定义当被divmod()调用时的行为(当左操作数不支持相应的操作时被调用) |
__ rpow__(self, other) | 定义当被power()调用或**运算时的行为(当左操作数不支持相应的操作时被调用) |
__ rlshift__(self, other) | 定义按位左移位的行为:<<(当左操作数不支持相应的操作时被调用) |
__ rrshift__(self, other) | 定义按位右移位的行为:>>(当左操作数不支持相应的操作时被调用) |
__ rand__(self, other) | 定义按位与操作的行为:&(当左操作数不支持相应的操作时被调用) |
__ rxor__(self, other) | 定义按位异或操作的行为:^(当左操作数不支持相应的操作时被调用) |
__ ror__(self, other) | 定义按位或操作的行为:丨(当左操作数不支持相应的操作时被调用) |
重写反运算魔法方法的时候,一定要注意操作数的顺序!
- 增量赋值运算的魔法方法
魔法方法 | 定义 |
---|---|
__ iadd__(self, other) | 定义赋值加法的行为:+= |
__ isub__(self, other) | 定义赋值减法的行为:-= |
__ imul__(self, other) | 定义赋值乘法的行为:*= |
__ itruediv__(self, other) | 定义赋值真除法的行为:/= |
__ ifloordiv__(self, other) | 定义赋值整数除法的行为://= |
__ imod__(self, other) | 定义赋值取模算法的行为:%= |
__ ipow__(self, other) | 定义赋值幂运算的行为:**= |
__ ilshift__(self, other) | 定义赋值按位左移位的行为:<<= |
__ irshift__(self, other) | 定义赋值按位右移位的行为:>>= |
__ iand__(self, other) | 定义赋值按位与操作的行为:&= |
__ ixor__(self, other) | 定义赋值按位异或操作的行为:^= |
__ ior__(self, other) | 定义赋值按位或操作的行为:丨= |
- 一元操作符的魔法方法
魔法方法 | 定义 |
---|---|
__ neg__(self) | 定义正号的行为:+x |
__ pos__(self) | 定义负号的行为:-x |
__ abs__(self) | 定义当被abs()调用时的行为 |
__ invert__(self) | 定义按位求反的行为:~x |