- 运算符重载有两个参数:
- self ——该对象本身
- other ——跟在运算符后面的对象
- 以下为重载运算符的参考列表
| 函数名称 | 参数列表 | 重载符号 |
|---|---|---|
| __add__ | (self, other) | + |
| __sub__ | (self, other) | - |
| __mul__ | (self, other) | * |
| __div__ | (self, other) | / |
| __floordiv__ | (self, other) | // |
| __mod__ | (self, other) | % |
| __pow__ | (self, other) | ** |
| __lshift__ | (self, other) | << |
| __rshift__ | (self, other) | >> |
| __and__ | (self, other) | & |
| __or__ | (self, other) | | |
| __xor__ | (self, other) | ^ |
以上函数名前增加 i,例如__ipow__则是重载 **= 运算符,__iadd__是重载 += 运算符。
| 函数名称 | 参数列表 | 重载符号 |
|---|---|---|
| __invert__ | (self) | ~ |
| __pos__ | (self) | + (一元运算符,例如:+a) |
| __neg__ | (self) | - (一元运算符,例如:-a) |
| 函数名称 | 参数列表 | 重载符号 |
|---|---|---|
| __eq__ | (self, other) | == |
| __ne__ | (self, other) | != |
| __lt__ | (self, other) | < |
| __gt__ | (self, other) | > |
| __le__ | (self, other) | <= |
| __ge__ | (self, other) | >= |
在我所见的教程中,这些运算符都有确切的含义。这给很多人带来一个刻板印象——这些符号的重载方式是有模板的。
事实上,这些符号没有被强制规定有什么意义,虽然人们一般按照原有的作用重载,但也可以重载为其他功能。
例如Django的orm中,查询语句Q重载了 | 以及其他位运算符,但作用却是逻辑运算。