- 運(yùn)算符重載有兩個(gè)參數(shù):
- self ——該對(duì)象本身
- other ——跟在運(yùn)算符后面的對(duì)象
- 以下為重載運(yùn)算符的參考列表
| 函數(shù)名稱 | 參數(shù)列表 | 重載符號(hào) |
|---|---|---|
| __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) | ^ |
以上函數(shù)名前增加 i,例如__ipow__則是重載 **= 運(yùn)算符,__iadd__是重載 += 運(yùn)算符。
| 函數(shù)名稱 | 參數(shù)列表 | 重載符號(hào) |
|---|---|---|
| __invert__ | (self) | ~ |
| __pos__ | (self) | + (一元運(yùn)算符,例如:+a) |
| __neg__ | (self) | - (一元運(yùn)算符,例如:-a) |
| 函數(shù)名稱 | 參數(shù)列表 | 重載符號(hào) |
|---|---|---|
| __eq__ | (self, other) | == |
| __ne__ | (self, other) | != |
| __lt__ | (self, other) | < |
| __gt__ | (self, other) | > |
| __le__ | (self, other) | <= |
| __ge__ | (self, other) | >= |
在我所見(jiàn)的教程中,這些運(yùn)算符都有確切的含義。這給很多人帶來(lái)一個(gè)刻板印象——這些符號(hào)的重載方式是有模板的。
事實(shí)上,這些符號(hào)沒(méi)有被強(qiáng)制規(guī)定有什么意義,雖然人們一般按照原有的作用重載,但也可以重載為其他功能。
例如Django的orm中,查詢語(yǔ)句Q重載了 | 以及其他位運(yùn)算符,但作用卻是邏輯運(yùn)算。