裝飾器 是 Python 最具特色的語法糖,本質是「接受函數、回傳函數」的高階函數。本文遵循「九步學習法」,從最簡單的函數包裝層層深入,掌握參數化、類裝飾器、保留元資料等進階技巧。
def myfunc():
print("myfunc() called.")
myfunc()
myfunc()
def deco(func):
print("before myfunc() called.")
func()
print("after myfunc() called.")
return func
myfunc = deco(myfunc) # 手動裝飾
myfunc()
myfunc()
@deco@deco
def myfunc():
print("myfunc() called.")
myfunc()
myfunc()
等同於 myfunc = deco(myfunc)。注意:裝飾器在 模組載入時 立即執行,故「before/after」只會印一次。
def deco(func):
def _deco():
print("before myfunc() called.")
func()
print("after myfunc() called.")
return _deco
@deco
def myfunc():
print("myfunc() called.")
return 'ok'
myfunc()
myfunc()
現在每次呼叫 myfunc() 都會印 before/after。
def deco(func):
def _deco(a, b):
print("before myfunc() called.")
ret = func(a, b)
print(f"after myfunc() called. result: {ret}")
return ret
return _deco
@deco
def myfunc(a, b):
print(f"myfunc({a},{b}) called.")
return a + b
myfunc(1, 2)
myfunc(3, 4)
*args, **kwargsdef deco(func):
def _deco(*args, **kwargs):
print(f"before {func.__name__} called.")
ret = func(*args, **kwargs)
print(f"after {func.__name__} called. result: {ret}")
return ret
return _deco
@deco
def myfunc(a, b):
return a + b
@deco
def myfunc2(a, b, c):
return a + b + c
def deco(arg):
def _deco(func):
def __deco():
print(f"before {func.__name__} called [{arg}].")
func()
print(f"after {func.__name__} called [{arg}].")
return __deco
return _deco
@deco("mymodule")
def myfunc():
print("myfunc() called.")
@deco("module2")
def myfunc2():
print("myfunc2() called.")
結構:deco(arg) 回傳真正的裝飾器 _deco,再裝飾函數。
class Deco:
def __init__(self, arg):
self.arg = arg
def __call__(self, func):
def wrapper(*args, **kwargs):
print(f"before {func.__name__} [{self.arg}]")
ret = func(*args, **kwargs)
print(f"after {func.__name__} [{self.arg}]")
return ret
return wrapper
@Deco("class-based")
def myfunc():
print("myfunc() called.")
functools.wraps 保留原函數元資料from functools import wraps
def deco(func):
@wraps(func) # 複製 __name__, __doc__, __module__, __annotations__ 等
def wrapper(*args, **kwargs):
print("before")
return func(*args, **kwargs)
return wrapper
@deco
def myfunc():
"""這是文件字串"""
pass
print(myfunc.__name__) # 'myfunc' (而非 'wrapper')
print(myfunc.__doc__) # '這是文件字串'
@timer, @log_calls@login_required, @permission('admin')@lru_cache, @cache(ttl=60)@retry(times=3), @circuit_breaker@validate(schema)return wrapper → 裝飾後函數變 None。@wraps → 除錯、文檔生成、序列化失效。TypeError。functools.wraps 或 functools.update_wrapper。__call__ 保持可呼叫性。九步走完,裝飾器不再是黑魔法,而是你工具箱裡最鋒利的瑞士刀。