# Python 運算符重載
> 原文: [https://thepythonguru.com/python-operator-overloading/](https://thepythonguru.com/python-operator-overloading/)
* * *
于 2020 年 1 月 7 日更新
* * *
您已經看到可以使用`+`運算符添加數字,并同時連接字符串。 這是可能的,因為`int`類和`str`類都重載了`+`運算符。 運算符實際上是在各個類中定義的方法。 運算符的定義方法稱為運算符重載。 例如:要對自定義對象使用`+`運算符,您需要定義一個名為`__add__`的方法。
讓我們舉個例子來更好地理解
```py
import math
class Circle:
? ? def __init__(self, radius):
? ? ? ? self.__radius = radius
? ? def setRadius(self, radius):
? ? ? ? self.__radius = radius
? ? def getRadius(self):
? ? ? ? return self.__radius
? ? def area(self):
? ? ? ? return math.pi * self.__radius ** 2
? ? def __add__(self, another_circle):
? ? ? ? return Circle( self.__radius + another_circle.__radius )
c1 = Circle(4)
print(c1.getRadius())
c2 = Circle(5)
print(c2.getRadius())
c3 = c1 + c2 # This became possible because we have overloaded + operator by adding a ? ?method named __add__
print(c3.getRadius())
```
**預期輸出**:
```py
4
5
9
```
```py
import math
class Circle:
def __init__(self, radius):
self.__radius = radius
def setRadius(self, radius):
self.__radius = radius
def getRadius(self):
return self.__radius
def area(self):
return math.pi * self.__radius ** 2
def __add__(self, another_circle):
return Circle( self.__radius + another_circle.__radius )
c1 = Circle(4)
print(c1.getRadius())
c2 = Circle(5)
print(c2.getRadius())
c3 = c1 + c2 # This became possible because we have overloaded + operator by adding a method named __add__
print(c3.getRadius())
```
在上面的示例中,我們添加了`__add__()`方法,該方法允許使用`+`運算符添加兩個圓形對象。 在`__add__()`方法內部,我們正在創建一個新對象并將其返回給調用者。
Python 還有許多其他特殊方法,例如`__add__()`,請參見下面的列表。
| 運算符 | 函數 | 方法說明 |
| --- | --- | --- |
| `+` | `__add__(self, other)` | 加法 |
| `*` | `__mul__(self, other)` | 乘法 |
| `-` | `__sub__(self, other)` | 減法 |
| `%` | `__mod__(self, other)` | 余數 |
| `/` | `__truediv__(self, other)` | 除法 |
| `<` | `__lt__(self, other)` | 小于 |
| `<=` | `__le__(self, other)` | 小于或等于 |
| `==` | `__eq__(self, other)` | 等于 |
| `!=` | `__ne__(self, other)` | 不等于 |
| `>` | `__gt__(self, other)` | 大于 |
`>=`,`__ge__(self, other)`,大于或等于`[index]`,`__getitem__(self, index)`,索引運算符`in`,`__contains__(self, value)`,檢查成員資格`len`,`__len__(self)`,元素數`str`,`__str__(self)`的字符串表示形式
下面的程序使用上面提到的一些函數來重載運算符。
```py
import math
class Circle:
? ? def __init__(self, radius):
? ? ? ? self.__radius = radius
? ? def setRadius(self, radius):
? ? ? ? self.__radius = radius
? ? def getRadius(self):
? ? ? ? return self.__radius
? ? def area(self):
? ? ? ? return math.pi * self.__radius ** 2
? ? def __add__(self, another_circle):
? ? ? ? return Circle( self.__radius + another_circle.__radius )
? ? def __gt__(self, another_circle):
? ? ? ? return self.__radius > another_circle.__radius
? ? def __lt__(self, another_circle):
? ? ? ? return self.__radius < another_circle.__radius
? ? def __str__(self):
? ? ? ? return "Circle with radius " + str(self.__radius)
c1 = Circle(4)
print(c1.getRadius())
c2 = Circle(5)
print(c2.getRadius())
c3 = c1 + c2
print(c3.getRadius())
print( c3 > c2) # Became possible because we have added __gt__ method
print( c1 < c2) # Became possible because we have added __lt__ method
print(c3) # Became possible because we have added __str__ method
```
**預期輸出**:
```py
4
5
9
True
True
Circle with radius 9
```
```py
import math
class Circle:
def __init__(self, radius):
self.__radius = radius
def setRadius(self, radius):
self.__radius = radius
def getRadius(self):
return self.__radius
def area(self):
return math.pi * self.__radius ** 2
def __add__(self, another_circle):
return Circle( self.__radius + another_circle.__radius )
def __gt__(self, another_circle):
return self.__radius > another_circle.__radius
def __lt__(self, another_circle):
return self.__radius < another_circle.__radius
def __str__(self):
return "Circle with radius " + str(self.__radius)
c1 = Circle(4)
print(c1.getRadius())
c2 = Circle(5)
print(c2.getRadius())
c3 = c1 + c2
print(c3.getRadius())
print( c3 > c2) # Became possible because we have added __gt__ method
print( c1 < c2) # Became possible because we have added __lt__ method
print(c3) # Became possible because we have added __str__ method
```
下一課是[繼承和多態](/python-inheritance-and-polymorphism/)。
* * *
* * *
- 初級 Python
- python 入門
- 安裝 Python3
- 運行 python 程序
- 數據類型和變量
- Python 數字
- Python 字符串
- Python 列表
- Python 字典
- Python 元組
- 數據類型轉換
- Python 控制語句
- Python 函數
- Python 循環
- Python 數學函數
- Python 生成隨機數
- Python 文件處理
- Python 對象和類
- Python 運算符重載
- Python 繼承與多態
- Python 異常處理
- Python 模塊
- 高級 Python
- Python *args和**kwargs
- Python 生成器
- Python 正則表達式
- 使用 PIP 在 python 中安裝包
- Python virtualenv指南
- Python 遞歸函數
- __name__ == "__main__"是什么?
- Python Lambda 函數
- Python 字符串格式化
- Python 內置函數和方法
- Python abs()函數
- Python bin()函數
- Python id()函數
- Python map()函數
- Python zip()函數
- Python filter()函數
- Python reduce()函數
- Python sorted()函數
- Python enumerate()函數
- Python reversed()函數
- Python range()函數
- Python sum()函數
- Python max()函數
- Python min()函數
- Python eval()函數
- Python len()函數
- Python ord()函數
- Python chr()函數
- Python any()函數
- Python all()函數
- Python globals()函數
- Python locals()函數
- 數據庫訪問
- 安裝 Python MySQLdb
- 連接到數據庫
- MySQLdb 獲取結果
- 插入行
- 處理錯誤
- 使用fetchone()和fetchmany()獲取記錄
- 常見做法
- Python:如何讀取和寫入文件
- Python:如何讀取和寫入 CSV 文件
- 用 Python 讀寫 JSON
- 用 Python 轉儲對象