Python函數(shù)裝飾器的使用教程
典型的函數(shù)裝飾器
以下示例定義了一個裝飾器,輸出函數(shù)的運行時間:

函數(shù)裝飾器和閉包緊密結合,入參func代表被裝飾函數(shù),通過自由變量綁定后,調用函數(shù)并返回結果。
使用clock裝飾器:
import time
from clockdeco import clock
@clock
def snooze(seconds):
time.sleep(seconds)
@clock
def factorial(n):
return 1 if n < 2 else n*factorial(n-1)
if __name__=='__main__':
print('*' * 40, 'Calling snooze(.123)')
snooze(.123)
print('*' * 40, 'Calling factorial(6)')
print('6! =', factorial(6)) # 6!指6的階乘
輸出結果:

這是裝飾器的典型行為:把被裝飾的函數(shù)換成新函數(shù),二者接受相同的參數(shù),而且返回被裝飾的函數(shù)本該返回的值,同時還會做些額外操作。
值得注意的是factorial()是個遞歸函數(shù),從結果來看,每次遞歸都用到了裝飾器,打印了運行時間,這是因為如下代碼:
@clock
def factorial(n):
return 1 if n < 2 else n*factorial(n-1)
等價于:
def factorial(n):
return 1 if n < 2 else n*factorial(n-1)
factorial = clock(factorial)
factorial引用的是clock(factorial)函數(shù)的返回值,也就是裝飾器內部函數(shù)clocked,每次調用factorial(n),執(zhí)行的都是clocked(n)。
疊放裝飾器
@d1
@d2
def f():
print("f")
等價于:
def f():
print("f")
f = d1(d2(f))
參數(shù)化裝飾器
怎么讓裝飾器接受參數(shù)呢?答案是:創(chuàng)建一個裝飾器工廠函數(shù),把參數(shù)傳給它,返回一個裝飾器,然后再把它應用到要裝飾的函數(shù)上。
示例如下:
registry = set()
def register(active=True):
def decorate(func):
print('running register(active=%s)->decorate(%s)'
% (active, func))
if active:
registry.add(func)
else:
registry.discard(func)
return func
return decorate
@register(active=False)
def f1():
print('running f1()')
# 注意這里的調用
@register()
def f2():
print('running f2()')
def f3():
print('running f3()')
register是一個裝飾器工廠函數(shù),接受可選參數(shù)active默認為True,內部定義了一個裝飾器decorate并返回。需要注意的是裝飾器工廠函數(shù),即使不傳參數(shù),也要加上小括號調用,比如@register()。
再看一個示例:
import time
DEFAULT_FMT = '[{elapsed:0.8f}s] {name}({args}) -> {result}'
# 裝飾器工廠函數(shù)
def clock(fmt=DEFAULT_FMT):
# 真正的裝飾器
def decorate(func):
# 包裝被裝飾的函數(shù)
def clocked(*_args):
t0 = time.time()
# _result是被裝飾函數(shù)返回的真正結果
_result = func(*_args)
elapsed = time.time() - t0
name = func.__name__
args = ', '.join(repr(arg) for arg in _args)
result = repr(_result)
# **locals()返回clocked的局部變量
print(fmt.format(**locals()))
return _result
return clocked
return decorate
if __name__ == '__main__':
@clock()
def snooze(seconds):
time.sleep(seconds)
for i in range(3):
snooze(.123)
這是給典型的函數(shù)裝飾器添加了參數(shù)fmt,裝飾器工廠函數(shù)增加了一層嵌套,示例中一共有3個def。
標準庫中的裝飾器
Python內置了三個用于裝飾方法的函數(shù):property、classmethod和staticmethod,這會在將來的文章中講到。本文介紹functools中的三個裝飾器:functools.wraps、functools.lru_cache和functools.singledispatch。
functools.wraps
Python函數(shù)裝飾器在實現(xiàn)的時候,被裝飾后的函數(shù)其實已經是另外一個函數(shù)了(函數(shù)名等函數(shù)屬性會發(fā)生改變),為了不影響,Python的functools包中提供了一個叫wraps的裝飾器來消除這樣的副作用(它能保留原有函數(shù)的名稱和函數(shù)屬性)。
示例,不加wraps:
def my_decorator(func):
def wrapper(*args, **kwargs):
'''decorator'''
print('Calling decorated function...')
return func(*args, **kwargs)
return wrapper
@my_decorator
def example():
"""Docstring"""
print('Called example function')
print(example.__name__, example.__doc__)
# 輸出wrapper decorator
加wraps:
import functools
def my_decorator(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
'''decorator'''
print('Calling decorated function...')
return func(*args, **kwargs)
return wrapper
@my_decorator
def example():
"""Docstring"""
print('Called example function')
print(example.__name__, example.__doc__)
# 輸出example Docstring
functools.lru_cache
lru是Least Recently Used的縮寫,它是一項優(yōu)化技術,把耗時的函數(shù)的結果保存起來,避免傳入相同的參數(shù)時重復計算。
示例:
import functools
from clockdeco import clock
@functools.lru_cache()
@clock
def fibonacci(n):
if n < 2:
return n
return fibonacci(n-2) + fibonacci(n-1)
if __name__=='__main__':
print(fibonacci(6))
優(yōu)化了遞歸算法,執(zhí)行時間會減半。
注意,lru_cache可以使用兩個可選的參數(shù)來配置,它的簽名如下:
functools.lru_cache(maxsize=128, typed=False)
- maxsize:最大存儲數(shù)量,緩存滿了以后,舊的結果會被扔掉。
- typed:如果設為True,那么會把不同參數(shù)類型得到的結果分開保存,即把通常認為相等的浮點數(shù)和整型參數(shù)(如1和1.0)區(qū)分開。
functools.singledispatch
Python3.4的新增語法,可以用來優(yōu)化函數(shù)中的大量if/elif/elif。使用@singledispatch裝飾的普通函數(shù)會變成泛函數(shù):根據第一個參數(shù)的類型,以不同方式執(zhí)行相同操作的一組函數(shù)。所以它叫做single dispatch,單分派。
根據多個參數(shù)進行分派,就是多分派了。
示例,生成HTML,顯示不同類型的Python對象:
import html
def htmlize(obj):
content = html.escape(repr(obj))
return '<pre>{}</pre>'.format(content)
因為Python不支持重載方法或函數(shù),所以就不能使用不同的簽名定義htmlize的變體,只能把htmlize變成一個分派函數(shù),使用if/elif/elif,調用專門的函數(shù),比如htmlize_str、htmlize_int等。時間一長htmlize會變得很大,跟各個專門函數(shù)之間的耦合也很緊密,不便于模塊擴展。
@singledispatch經過深思熟慮后加入到了標準庫,來解決這類問題:
from functools import singledispatch
from collections import abc
import numbers
import html
@singledispatch
def htmlize(obj):
# 基函數(shù) 這里不用寫if/elif/elif來分派了
content = html.escape(repr(obj))
return '<pre>{}</pre>'.format(content)
@htmlize.register(str)
def _(text):
# 專門函數(shù)
content = html.escape(text).replace('\n', '<br>\n')
return '<p>{0}</p>'.format(content)
@htmlize.register(numbers.Integral)
def _(n):
# 專門函數(shù)
return '<pre>{0} (0x{0:x})</pre>'.format(n)
@htmlize.register(tuple)
@htmlize.register(abc.MutableSequence)
def _(seq):
# 專門函數(shù)
inner = '</li>\n<li>'.join(htmlize(item) for item in seq)
return '<ul>\n<li>' + inner + '</li>\n</ul>'
@singledispatch裝飾了基函數(shù)。專門函數(shù)使用@<<base_function>>.register(<<type>>)裝飾,它的名字不重要,命名為_,簡單明了。
這樣編寫代碼后,Python會根據第一個參數(shù)的類型,調用相應的專門函數(shù)。
小結
本文首先介紹了典型的函數(shù)裝飾器:把被裝飾的函數(shù)換成新函數(shù),二者接受相同的參數(shù),而且返回被裝飾的函數(shù)本該返回的值,同時還會做些額外操作。接著介紹了裝飾器的兩個高級用法:疊放裝飾器和參數(shù)化裝飾器,它們都會增加函數(shù)的嵌套層級。最后介紹了3個標準庫中的裝飾器:保留原有函數(shù)屬性的functools.wraps、緩存耗時的函數(shù)結果的functools.lru_cache和優(yōu)化if/elif/elif代碼的functools.singledispatch。
參考資料:
《流暢的Python》https://github.com/fluentpython/example-code/tree/master/07-closure-deco
https://blog.csdn.net/liuzonghao88/article/details/103586634
以上就是Python函數(shù)裝飾器高級用法的詳細內容,更多關于Python函數(shù)裝飾器用法的資料請關注腳本之家其它相關文章!
相關文章
django admin 后臺實現(xiàn)三級聯(lián)動的示例代碼
這篇文章主要介紹了django admin 后臺實現(xiàn)三級聯(lián)動的示例代碼,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2018-06-06
python接口自動化(十七)--Json 數(shù)據處理---一次爬坑記(詳解)
這篇文章主要介紹了python Json 數(shù)據處理,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2019-04-04
已安裝Pytorch卻提示no?moudle?named?'torch'(沒有名稱為torch
這篇文章主要給大家介紹了關于已安裝Pytorch卻提示no?moudle?named?'torch'(沒有名稱為torch的模塊)的相關資料,當提示"No module named 'torch'"時,可能是由于安裝的Pytorch版本與當前環(huán)境不匹配導致的,需要的朋友可以參考下2023-11-11
Python 比較文本相似性的方法(difflib,Levenshtein)
今天小編就為大家分享一篇Python 比較文本相似性的方法(difflib,Levenshtein),具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2018-10-10

