python操作符重载特殊方法列表
Posted 詩和遠方
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python操作符重载特殊方法列表相关的知识,希望对你有一定的参考价值。
如下表,python类只要实现了右边所示特殊名称的方法,就实现了操作符重载,可使用左边的操作符语法:
Common Syntax | Special Method Form |
---|---|
a + b | a._add_(b); alternatively b._radd_(a) |
a − b | a._sub_(b); alternatively b._rsub_(a) |
a b | a._mul_(b); alternatively b._rmul_(a) |
a / b | a._truediv_(b); alternatively b._rtruediv_(a) |
a // b | a._floordiv_(b); alternatively b._rfloordiv_(a) |
a % b | a._mod_(b); alternatively b._rmod_(a) |
a b | a._pow_(b); alternatively b._rpow_(a) |
a << b | a._lshift_(b); alternatively b._rlshift_(a) |
a >> b | a._rshift_(b); alternatively b._rrshift_(a) |
a & b | a._and_(b); alternatively b._rand_(a) |
a ˆ b | a._xor_(b); alternatively b._rxor_(a) |
a | b | a._or_(b); alternatively b._ror_(a) |
a += b | a._iadd_(b) |
a −= b | a._isub_(b) |
a = b | a._imul_(b) |
… … | |
+a | a._pos_() |
−a | a._neg_() |
˜a | a._invert_() |
abs(a) | a._abs_() |
a < b | a._lt_(b) |
a <= b | a._le_(b) |
a > b | a._gt_(b) |
a >= b | a._ge_(b) |
a == b | a._eq_(b) |
a != b | a._ne_(b) |
v in a | a._contains_(v) |
a[k] | a._getitem_(k) |
a[k] = v | a._setitem_(k,v) |
del a[k] | a._delitem_(k) |
a(arg1, arg2, …) | a._call_(arg1, arg2, …) |
len(a) | a._len_() |
hash(a) | a._hash_() |
iter(a) | a._iter_() |
next(a) | a._next_() |
bool(a) | a._bool_() |
float(a) | a._float_() |
int(a) | a._int_() |
repr(a) | a._repr_() |
reversed(a) | a._reversed_() |
str(a) | a._str_() |
以上是关于python操作符重载特殊方法列表的主要内容,如果未能解决你的问题,请参考以下文章
Python入门-6面向对象编程:10特殊方法和运算符重载-特殊属性