在軟體開發中,日誌記錄、效能監控、事務管理、權限校驗等「橫切關注點」往往散落在業務邏輯各處,導致代碼重複、耦合度高。裝飾器模式通過「包裝」目標函數,在不修改原函數定義與調用點的前提下,靈活注入橫切邏輯,是 Python 實現 AOP 的核心利器。
import time
def foo():
start = time.perf_counter()
print("in foo()")
end = time.perf_counter()
print(f"used: {end - start:.6f}s")
foo()
缺點:侵入業務代碼,違反單一職責原則,難以複用。
def timeit(func):
start = time.perf_counter()
func()
end = time.perf_counter()
print(f"used: {end - start:.6f}s")
timeit(foo) # 調用方式改變,所有調用點需修改
缺點:調用語法改變,若函數被多處調用或作為 API 供外部使用,改造成本極高。
def timeit(func):
def wrapper():
start = time.perf_counter()
func()
end = time.perf_counter()
print(f"used: {end - start:.6f}s")
return wrapper
foo = timeit(foo) # 替換原函數引用
foo() # 調用方式不變
此時 timeit 就是一個裝飾器:接收函數,返回增強後的函數。foo = timeit(foo) 相當於「裝飾」了 foo。
@
@timeit
def foo():
print("in foo()")
foo() # 等價於 foo = timeit(foo); foo()
@ 僅是語法糖,編譯時自動展開為賦值語句,零運行時開銷。
import functools
import time
def timer(func):
@functools.wraps(func) # 保留 __name__, __doc__ 等元數據
def wrapper(*args, **kwargs):
start = time.perf_counter()
result = func(*args, **kwargs)
end = time.perf_counter()
print(f"[{func.__name__}] elapsed: {end - start:.6f}s")
return result
return wrapper
@timer
def compute(a: int, b: int) -> int:
"""計算兩數之和"""
time.sleep(0.1)
return a + b
print(compute(3, 5)) # 輸出耗時並返回 8
print(compute.__name__, compute.__doc__) # 元數據完好
關鍵點:
*args, **kwargs 透傳任意參數。functools.wraps 避免反射/序列化/除錯時出現 wrapper 而非原函數名。
def repeat(times: int):
"""返回一個裝飾器,使被裝飾函數重複執行 N 次"""
def decorator(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
for _ in range(times):
result = func(*args, **kwargs)
return result
return wrapper
return decorator
@repeat(3)
def greet(name):
print(f"Hello, {name}!")
greet("Alice") # 連續打印三次
| 裝飾器 | 用途 | 典型場景 |
|---|---|---|
@staticmethod | 定義靜態方法,無 self/cls | 工具函數、工廠方法 |
@classmethod | 接收 cls,可訪問類屬性 | 替代構造器、單例模式 |
@property | 將方法轉為屬性訪問 | 封裝 getter/setter、計算屬性 |
functools 進階裝飾器@functools.wraps已在上文示例,核心作用:複製 __module__, __name__, __qualname__, __doc__, __annotations__ 等屬性,並更新 __dict__。
@functools.lru_cache 記憶化
@functools.lru_cache(maxsize=128)
def fib(n):
if n < 2: return n
return fib(n-1) + fib(n-2)
print(fib(30)) # 瞬間返回,避免指數級遞歸
@functools.total_ordering 自動補全比較方法
@functools.total_ordering
class Version:
def __init__(self, major, minor, patch):
self.tuple = (major, minor, patch)
def __eq__(self, other): return self.tuple == other.tuple
def __lt__(self, other): return self.tuple < other.tuple
v1 = Version(1, 2, 0)
v2 = Version(1, 3, 0)
print(v1 < v2, v1 <= v2, v1 > v2, v1 >= v2) # 全部自動可用
在 AOP 術語中:
save_ 開頭的方法」)。Python 裝飾器天然實現 Around Advice(環繞通知),配合 inspect 或第三方庫(如 aspectlib)可構建更豐富的 AOP 框架。
@functools.wraps + inspect.Signature 完美保留類型提示。try/finally 確保資源釋放,raise 原始異常。func.__wrapped__ 繞過裝飾器直接測試。裝飾器是 Python 最具表達力的特性之一,從簡單的計時器到企業級 AOP 框架,核心思想始終是「關注點分離」。掌握 functools 工具箱、理解閉包與描述符機制,能讓你編寫出既優雅又健壯的可復用組件。