Python 的運算符重載機制允許自定義類通過實現特定魔術方法(雙下劃線方法)來支持原生運算符(+, -, *, ==, [], with 等),讓對象行為如內置類型般自然。本文系統梳理所有可重載運算符、對應魔術方法、實戰設計模式、反射操作與常見陷阱。
一、 運算符與魔術方法對照表
| 類別 | 運算符/語法 | 魔術方法 | 反射/逆序方法 | 說明 |
| 一元運算符 | -obj | __neg__(self) | | 取負 |
+obj | __pos__(self) | | 正號 |
~obj | __invert__(self) | | 按位取反 |
abs(obj) | __abs__(self) | | 絕對值/模 |
bool(obj) | __bool__(self) | | 真值測試 (Py3),Py2 為 __nonzero__ |
len(obj) | __len__(self) | | 長度,返回非負整數 |
| 類別 | 運算符 | 正向方法 | 反射方法 | 說明 |
| 二元算術 | a + b | __add__(self, other) | __radd__(self, other) | 加法 |
a - b | __sub__(self, other) | __rsub__(self, other) | 減法 |
a * b | __mul__(self, other) | __rmul__(self, other) | 乘法 |
a / b | __truediv__(self, other) | __rtruediv__(self, other) | 真除法 (Py3) |
a // b | __floordiv__(self, other) | __rfloordiv__(self, other) | 地板除 |
a % b | __mod__(self, other) | __rmod__(self, other) | 取模 |
a ** b | __pow__(self, other[, modulo]) | __rpow__(self, other) | 冪運算,可選三參數 |
a @ b | __matmul__(self, other) | __rmatmul__(self, other) | 矩陣乘法 (Py3.5+) |
| 類別 | 運算符 | 魔術方法 | 說明 |
| 比較運算符 | a == b | __eq__(self, other) | 相等(建議實現則同時實現 __hash__) |
a != b | __ne__(self, other) | 不等 (Py3 默認委託 __eq__ 取反) |
a < b | __lt__(self, other) | 小於 (排序關鍵,sorted/list.sort 依賴) |
a > b | __gt__(self, other) | 大於 |
a <= b | __le__(self, other) | 小於等於 |
a >= b | __ge__(self, other) | 大於等於 |
| 類別 | 語法 | 魔術方法 | 說明 |
| 容器/訪問 | obj[key] | __getitem__(self, key) | 索引訪問,支援切片對象 |
obj[key] = val | __setitem__(self, key, val) | 索引賦值 |
del obj[key] | __delitem__(self, key) | 索引刪除 |
key in obj | __contains__(self, key) | 成員測試 |
| 迭代/可調用 | iter(obj) | __iter__(self) | 返回迭代器對象 (需實現 __next__) |
next(obj) | __next__(self) | 迭代器協議,拋出 StopIteration 結束 |
obj(*args, **kwargs) | __call__(self, *args, **kwargs) | 可調用對象(函數對象/裝飾器/構造器語法糖) |
| 類別 | 語法 | 魔術方法 | 說明 |
| 上下文管理 | with obj: | __enter__(self), __exit__(self, exc_type, exc_val, exc_tb) | 資源管理、事務、鎖 |
| 屬性訪問 | obj.attr | __getattr__, __setattr__, __delattr__, __getattribute__ | 屬性訪問攔截 |
| 字符串表示 | str(obj)/print(obj) | __str__(self) | 用戶友好表示 |
| repr(obj) | __repr__(self) | 開發者友好表示 (理想情況 eval(repr(obj)) == obj) |
| 哈希 | hash(obj) | __hash__(self) | 可哈希對象必須不可變,__eq__ 一致則 __hash__ 必須一致 |
| 複製 | copy.copy/deepcopy | __copy__, __deepcopy__ | 自定義複製行為 |
| 序列化 | pickle | __getstate__, __setstate__, __reduce__ | 自定義序列化 |
二、 實戰設計模式
1. 數值類型:不可變值對象
from functools import total_ordering
import math
@total_ordering # 自動根據 __eq__ 和 __lt__ 生成其餘比較方法
class Vector:
__slots__ = ('x', 'y') # 節省內存,禁止動態屬性
def __init__(self, x: float, y: float):
self.x, self.y = float(x), float(y)
# 算術運算:返回新實例,保持不可變
def __add__(self, other: 'Vector') -> 'Vector':
if not isinstance(other, Vector): return NotImplemented
return Vector(self.x + other.x, self.y + other.y)
def __sub__(self, other: 'Vector') -> 'Vector':
if not isinstance(other, Vector): return NotImplemented
return Vector(self.x - other.x, self.y - other.y)
def __mul__(self, scalar: float) -> 'Vector':
if not isinstance(scalar, (int, float)): return NotImplemented
return Vector(self.x * scalar, self.y * scalar)
__rmul__ = __mul__ # 支持 scalar * vector
def __matmul__(self, other: 'Vector') -> float: # 點積
if not isinstance(other, Vector): return NotImplemented
return self.x * other.x + self.y * other.y
# 比較:按模長
def __eq__(self, other: object) -> bool:
if not isinstance(other, Vector): return NotImplemented
return self.x == other.x and self.y == other.y
def __lt__(self, other: 'Vector') -> bool:
if not isinstance(other, Vector): return NotImplemented
return self.x**2 + self.y**2 < other.x**2 + other.y**2
def __abs__(self) -> float:
return math.hypot(self.x, self.y)
def __len__(self) -> int:
return 2 # 維度
def __getitem__(self, index: int) -> float:
if index == 0: return self.x
if index == 1: return self.y
raise IndexError("Vector index out of range")
def __iter__(self):
yield self.x
yield self.y
def __repr__(self) -> str:
return f"Vector({self.x}, {self.y})"
def __str__(self) -> str:
return f"({self.x}, {self.y})"
def __hash__(self) -> int:
return hash((self.x, self.y))
# 使用
v1, v2 = Vector(3, 4), Vector(1, 2)
print(v1 + v2) # (4, 6)
print(v1 @ v2) # 11.0 (點積)
print(abs(v1)) # 5.0
print(v1[0]) # 3.0
print(sorted([v2, v1])) # [(1, 2), (3, 4)] 按模長排序
print(hash(v1)) # 可作字典鍵/集合元素
2. 容器類型:序列/映射協議
class MultiDict:
"""支援同鍵多值的字典"""
def __init__(self):
self._data = {}
def __setitem__(self, key, value):
self._data.setdefault(key, []).append(value)
def __getitem__(self, key):
vals = self._data.get(key)
if vals is None: raise KeyError(key)
return vals[-1] # 最後值
def getlist(self, key):
return self._data.get(key, [])
def __delitem__(self, key):
del self._data[key]
def __contains__(self, key):
return key in self._data
def __iter__(self):
return iter(self._data) # 迭代鍵
def __len__(self):
return len(self._data)
def __repr__(self):
return f"MultiDict({self._data})"
3. 上下文管理器:資源守衛
class Transaction:
def __init__(self, conn):
self.conn = conn
self._committed = False
def __enter__(self):
self.conn.begin()
return self
def __exit__(self, exc_type, exc_val, exc_tb):
if exc_type is None:
self.conn.commit()
self._committed = True
else:
self.conn.rollback()
return False # 不吞噬異常
# 使用
with Transaction(db_conn) as tx:
tx.conn.execute("INSERT ...")
# 異常自動回滾,正常自動提交
4. 可調用對象:策略/工廠/裝飾器
class RateLimiter:
def __init__(self, max_calls: int, period: float):
self.max_calls, self.period = max_calls, period
self.calls = []
def __call__(self, func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
now = time.time()
self.calls = [t for t in self.calls if now - t < self.period]
if len(self.calls) >= self.max_calls:
raise RuntimeError("Rate limit exceeded")
self.calls.append(now)
return func(*args, **kwargs)
return wrapper
@RateLimiter(10, 60) # 每分鐘最多 10 次
def api_call(): ...
三、 反射機制與 NotImplemented 協議
- 正向調用:
a + b → a.__add__(b)。
- 反射調用:若
a.__add__(b) 返回 NotImplemented(非 False!),Python 嘗試 b.__radd__(a)。
- 類型不支持:返回
NotImplemented 而非拋出異常,讓 Python 嘗試反射/內置回退。切勿返回 False 或拋出 TypeError(除非確定不支持任何類型)。
__radd__ 等反射方法參數順序:self 是右操作數,other 是左操作數。
四、 常見陷阱與最佳實踐
| 陷阱 | 後果 | 正確做法 |
可變對象實現 __hash__ | 放入 set/dict 後修改導致查找失效、內存洩漏 | 不可變對象才實現 __hash__;可變對象不實現__hash__ (繼承 object 默認 id 哈希) |
__eq__ 不對稱 | a==b != b==a,違反等價關係 | 始終檢查 isinstance(other, SelfType),返回 NotImplemented 而非 False |
| 修改內置類型運算符 | 無法修改 int, list 等內置類型 | 繼承或組合封裝 |
__getitem__ 不支援切片 | obj[1:3] 報錯 | 檢查 isinstance(key, slice),返回切片對象 |
__iter__ 返回 self 但無 __next__ | TypeError | 實現 __next__ 或返回單獨迭代器對象 |
| 濫用運算符導致語義混淆 | 代碼可讀性下降 (如 user + order 含義不明) | 僅對數學/容器/領域語義明確場景使用;複雜業務用具名方法 |
五、 總結
運算符重載是 Python 表達力的核心來源。遵循語義一致性(+ 即加法/合併,[] 即索引/鍵訪問)、不可變性與哈希協同、返回 NotImplemented 而非 False、配合 @total_ordering 減少樣板代碼。善用魔術方法,能讓你的類無縫融入 Python 生態(sum(), sorted(), with, in, len(), hash(), pickle 等),編寫出既 Pythonic 又高效的庫級代碼。