以下示例定義了一個(gè)裝飾器,輸出函數(shù)的運(yùn)行時(shí)間:
函數(shù)裝飾器和閉包緊密結(jié)合,入?yún)unc代表被裝飾函數(shù),通過自由變量綁定后,調(diào)用函數(shù)并返回結(jié)果。
使用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的階乘
輸出結(jié)果:
這是裝飾器的典型行為:把被裝飾的函數(shù)換成新函數(shù),二者接受相同的參數(shù),而且返回被裝飾的函數(shù)本該返回的值,同時(shí)還會(huì)做些額外操作。
值得注意的是factorial()是個(gè)遞歸函數(shù),從結(jié)果來看,每次遞歸都用到了裝飾器,打印了運(yùn)行時(shí)間,這是因?yàn)槿缦麓a:
@clock def factorial(n): return 1 if n 2 else n*factorial(n-1)
等價(jià)于:
def factorial(n): return 1 if n 2 else n*factorial(n-1) factorial = clock(factorial)
factorial引用的是clock(factorial)函數(shù)的返回值,也就是裝飾器內(nèi)部函數(shù)clocked,每次調(diào)用factorial(n),執(zhí)行的都是clocked(n)。
@d1 @d2 def f(): print("f")
等價(jià)于:
def f(): print("f") f = d1(d2(f))
怎么讓裝飾器接受參數(shù)呢?答案是:創(chuàng)建一個(gè)裝飾器工廠函數(shù),把參數(shù)傳給它,返回一個(gè)裝飾器,然后再把它應(yīng)用到要裝飾的函數(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()') # 注意這里的調(diào)用 @register() def f2(): print('running f2()') def f3(): print('running f3()')
register是一個(gè)裝飾器工廠函數(shù),接受可選參數(shù)active默認(rèn)為True,內(nèi)部定義了一個(gè)裝飾器decorate并返回。需要注意的是裝飾器工廠函數(shù),即使不傳參數(shù),也要加上小括號(hào)調(diào)用,比如@register()。
再看一個(gè)示例:
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ù)返回的真正結(jié)果 _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個(gè)def。
Python內(nèi)置了三個(gè)用于裝飾方法的函數(shù):property、classmethod和staticmethod,這會(huì)在將來的文章中講到。本文介紹functools中的三個(gè)裝飾器:functools.wraps、functools.lru_cache和functools.singledispatch。
Python函數(shù)裝飾器在實(shí)現(xiàn)的時(shí)候,被裝飾后的函數(shù)其實(shí)已經(jīng)是另外一個(gè)函數(shù)了(函數(shù)名等函數(shù)屬性會(huì)發(fā)生改變),為了不影響,Python的functools包中提供了一個(gè)叫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
lru是Least Recently Used的縮寫,它是一項(xiàng)優(yōu)化技術(shù),把耗時(shí)的函數(shù)的結(jié)果保存起來,避免傳入相同的參數(shù)時(shí)重復(fù)計(jì)算。
示例:
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í)行時(shí)間會(huì)減半。
注意,lru_cache可以使用兩個(gè)可選的參數(shù)來配置,它的簽名如下:
functools.lru_cache(maxsize=128, typed=False)
Python3.4的新增語法,可以用來優(yōu)化函數(shù)中的大量if/elif/elif。使用@singledispatch裝飾的普通函數(shù)會(huì)變成泛函數(shù):根據(jù)第一個(gè)參數(shù)的類型,以不同方式執(zhí)行相同操作的一組函數(shù)。所以它叫做single dispatch,單分派。
根據(jù)多個(gè)參數(shù)進(jìn)行分派,就是多分派了。
示例,生成HTML,顯示不同類型的Python對(duì)象:
import html def htmlize(obj): content = html.escape(repr(obj)) return 'pre>{}/pre>'.format(content)
因?yàn)镻ython不支持重載方法或函數(shù),所以就不能使用不同的簽名定義htmlize的變體,只能把htmlize變成一個(gè)分派函數(shù),使用if/elif/elif,調(diào)用專門的函數(shù),比如htmlize_str、htmlize_int等。時(shí)間一長htmlize會(huì)變得很大,跟各個(gè)專門函數(shù)之間的耦合也很緊密,不便于模塊擴(kuò)展。
@singledispatch經(jīng)過深思熟慮后加入到了標(biāo)準(zhǔn)庫,來解決這類問題:
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>\nli>'.join(htmlize(item) for item in seq) return 'ul>\nli>' + inner + '/li>\n/ul>'
@singledispatch裝飾了基函數(shù)。專門函數(shù)使用@base_function>>.register(type>>)裝飾,它的名字不重要,命名為_,簡單明了。
這樣編寫代碼后,Python會(huì)根據(jù)第一個(gè)參數(shù)的類型,調(diào)用相應(yīng)的專門函數(shù)。
本文首先介紹了典型的函數(shù)裝飾器:把被裝飾的函數(shù)換成新函數(shù),二者接受相同的參數(shù),而且返回被裝飾的函數(shù)本該返回的值,同時(shí)還會(huì)做些額外操作。接著介紹了裝飾器的兩個(gè)高級(jí)用法:疊放裝飾器和參數(shù)化裝飾器,它們都會(huì)增加函數(shù)的嵌套層級(jí)。最后介紹了3個(gè)標(biāo)準(zhǔn)庫中的裝飾器:保留原有函數(shù)屬性的functools.wraps、緩存耗時(shí)的函數(shù)結(jié)果的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ù)裝飾器高級(jí)用法的詳細(xì)內(nèi)容,更多關(guān)于Python函數(shù)裝飾器用法的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!
標(biāo)簽:商丘 江蘇 定西 酒泉 龍巖 云南 寧夏 金融催收
巨人網(wǎng)絡(luò)通訊聲明:本文標(biāo)題《Python函數(shù)裝飾器的使用教程》,本文關(guān)鍵詞 Python,函數(shù),裝飾,器,的,使用,;如發(fā)現(xiàn)本文內(nèi)容存在版權(quán)問題,煩請(qǐng)?zhí)峁┫嚓P(guān)信息告之我們,我們將及時(shí)溝通與處理。本站內(nèi)容系統(tǒng)采集于網(wǎng)絡(luò),涉及言論、版權(quán)與本站無關(guān)。