久久福利_99r_国产日韩在线视频_直接看av的网站_中文欧美日韩_久久一

您的位置:首頁技術(shù)文章
文章詳情頁

python 裝飾器的基本使用

瀏覽:35日期:2022-06-30 08:35:06
知識(shí)點(diǎn) 簡單的裝飾器 帶有參數(shù)的裝飾器 帶有自定義參數(shù)的裝飾器 類裝飾器 裝飾器嵌套 @functools.wrap裝飾器使用 基礎(chǔ)使用簡單的裝飾器

def my_decorator(func): def wrapper(): print(’wrapper of decorator’) func() return wrapper()def test(): print(’test done.’)test = my_decorator(test)test輸出:wrapper of decoratortest done.

這段代碼中,變量test指向了內(nèi)部函數(shù)wrapper(), 而內(nèi)部函數(shù)wrapper()中又會(huì)調(diào)用原函數(shù)test(),因此最后調(diào)用test()時(shí),就會(huì)打印’wrapper of decorator’ 然后輸出 ’test done.’

這里的函數(shù)my_decorator()就是一個(gè)裝飾器,它把真正需要執(zhí)行的函數(shù)test()包裹在其中,并且改變了它的行為,但是原函數(shù)test()不變。

上述代碼在Python中更簡單、更優(yōu)雅的表示:

def my_decorator(func): def wrapper(): print(’wrapper of decorator’) func() return wrapper()@my_decoratordef test(): print(’test done.’)test

這里的@, 我們稱為語法糖,@my_decorator就相當(dāng)于前面的test=my_decorator(test)語句

如果程序中又其他函數(shù)需要類似裝飾,只需要加上@decorator就可以,提高函數(shù)的重復(fù)利用和程序可讀性

帶有參數(shù)的裝飾器

def args_decorator(func): def wrapper(*args, **kwargs): print(’wrapper of decorator’) func(*args, **kwargs) return wrapper@args_decoratordef identity(name, message): print(’identity done.’) print(name, message)identity(’changhao’, ’hello’)輸出:wrapper of decoratoridentity done.changhao hello

通常情況下,會(huì)把a(bǔ)rgs和*kwargs,作為裝飾器內(nèi)部函數(shù)wrapper()的參數(shù)。 表示接受任意數(shù)量和類型的參數(shù)

帶有自定義參數(shù)的裝飾器

定義一個(gè)參數(shù),表示裝飾器內(nèi)部函數(shù)被執(zhí)行的次數(shù),可以寫成這個(gè)形式:

def repeat(num): def my_decorator(func): def wrapper(*args, **kwargs): for i in range(num):func(*args, **kwargs) return wrapper return my_decorator@repeat(3)def showname(message): print(message)showname(’changhao’)輸出:changhaochanghaochanghao類裝飾器

類也可以作裝飾器,類裝飾器主要依賴于函數(shù) __call__每當(dāng)調(diào)用一個(gè)示例時(shí),函數(shù)__call__()就會(huì)被執(zhí)行一次。

class Count: def __init__(self, func): self.func = func self.num_calls = 0 def __call__(self, *args, **kwargs): self.num_calls += 1 print(’num of calls is: {}’.format(self.num_calls)) return self.func(*args, **kwargs)@Countdef example(): print(’example done.’)example()example()輸出:num of calls is: 1example done.num of calls is: 2example done.

這里定義了類Count,初始化時(shí)傳入原函數(shù)func(),而__call__()函數(shù)表示讓變量num_calls自增1,然后打印,并且調(diào)用原函數(shù)。因此我們第一次調(diào)用函數(shù)example()時(shí),num_calls的值是1,而第一次調(diào)用時(shí),值變成了2。

裝飾器的嵌套

import functoolsdef my_decorator1(func): @functools.wraps(func) def wrapper(*args, **kwargs): print(’execute decorator1’) func(*args, **kwargs) return wrapperdef my_decorator2(func): @functools.wraps(func) def wrapper(*args, **kwargs): print(’execute decorator2’) func(*args, **kwargs) return wrapper@my_decorator1@my_decorator2def test2(message): print(message)test2(’changhao’)輸出:execute decorator1execute decorator2changhao類裝飾器

類也可以作裝飾器,類裝飾器主要依賴于函數(shù) __call__每當(dāng)調(diào)用一個(gè)示例時(shí),函數(shù)__call__()就會(huì)被執(zhí)行一次。

class Count: def __init__(self, func): self.func = func self.num_calls = 0 def __call__(self, *args, **kwargs): self.num_calls += 1 print(’num of calls is: {}’.format(self.num_calls)) return self.func(*args, **kwargs)@Countdef example(): print(’example done.’)example()example()輸出:num of calls is: 1example done.num of calls is: 2example done.

這里定義了類Count,初始化時(shí)傳入原函數(shù)func(),而__call__()函數(shù)表示讓變量num_calls自增1,然后打印,并且調(diào)用原函數(shù)。因此我們第一次調(diào)用函數(shù)example()時(shí),num_calls的值是1,而第一次調(diào)用時(shí),值變成了2。

裝飾器的嵌套

import functoolsdef my_decorator1(func): @functools.wraps(func) def wrapper(*args, **kwargs): print(’execute decorator1’) func(*args, **kwargs) return wrapperdef my_decorator2(func): @functools.wraps(func) def wrapper(*args, **kwargs): print(’execute decorator2’) func(*args, **kwargs) return wrapper@my_decorator1@my_decorator2def test2(message): print(message)test2(’changhao’)輸出:execute decorator1execute decorator2changhao@functools.wrap裝飾器使用

import functoolsdef my_decorator(func): @functools.wraps(func) def wrapper(*args, **kwargs): print(’wrapper of decorator’) func(*args, **kwargs) return wrapper@my_decoratordef test3(message): print(message)test3.__name__ 輸出test3

通常使用內(nèi)置的裝飾器@functools.wrap,他會(huì)保留原函數(shù)的元信息(也就是將原函數(shù)的元信息,拷貝到對(duì)應(yīng)的裝飾器里)

裝飾器用法實(shí)例身份認(rèn)證

import functoolsdef authenticate(func): @functools.wraps(func) def wrapper(*args, **kwargs): request = args[0] if check_user_logged_in(request): return func(*args, **kwargs) else: raise Exception(’Authentication failed’) return wrapper@authenticatedef post_comment(request): pass

這段代碼中,定義了裝飾器authenticate;而函數(shù)post_comment(),則表示發(fā)表用戶對(duì)某篇文章的評(píng)論。每次調(diào)用這個(gè)函數(shù)前,都會(huì)檢查用戶是否處于登錄狀態(tài),如果是登錄狀態(tài),則允許這項(xiàng)操作;如果沒有登錄,則不允許。

日志記錄

import timeimport functoolsdef log_execution_time(func): @functools.wraps(func) def wrapper(*args, **kwargs): start = time.perf_counter() res = func(*args, **kwargs) end = time.perf_counter() print(’{} took {} ms’.format(func.__name__, (end - start) * 1000)) return wrapper@log_execution_timedef calculate_similarity(times): pass

這里裝飾器log_execution_time記錄某個(gè)函數(shù)的運(yùn)行時(shí)間,并返回其執(zhí)行結(jié)果。如果你想計(jì)算任何函數(shù)的執(zhí)行時(shí)間,在這個(gè)函數(shù)上方加上@log_execution_time即可。

總結(jié)

所謂裝飾器,其實(shí)就是通過裝飾器函數(shù),來修改原函數(shù)的一些功能,使得原函數(shù)不需要修改。

以上就是python 裝飾器的基本使用的詳細(xì)內(nèi)容,更多關(guān)于python 裝飾器的資料請(qǐng)關(guān)注好吧啦網(wǎng)其它相關(guān)文章!

標(biāo)簽: Python 編程
相關(guān)文章:
主站蜘蛛池模板: 玖草在线视频 | 日日爽 | 亚洲一区中文字幕在线观看 | 日日夜夜狠狠 | 成人免费看片 | 超碰一区二区三区 | 久久少妇免费看 | 亚洲网站在线免费观看 | 久久999视频| 天堂va在线高清一区 | 五月天婷婷综合 | 国产精品久久久久久一区二区三区 | 久久中文视频 | 四虎5151久久欧美毛片 | 在线播放一区二区三区 | 国产精品久久久久久久免费大片 | 日韩国产在线播放 | 欧美午夜一区二区三区 | 成人免费一区二区三区视频网站 | 久草免费在线视频 | 午夜视频网 | 国产高清精品一区 | 亚洲日韩欧美一区二区在线 | 国产亚洲一区二区三区 | 999久久久国产精品 免费视频一区 | 亚洲一区中文字幕在线 | 免费在线视频精品 | 夜夜爽99久久国产综合精品女不卡 | 精品国产不卡一区二区三区 | 亚洲免费观看 | 高清视频一区二区三区 | 欧美成人性生活 | 91精品国产综合久久久久 | 九色porny丨国产精品 | 99久久久久国产精品免费 | 做视频免费观看网站 | 91在线看片 | 国产综合精品一区二区三区 | 黄色网页大全 | 国产午夜视频 | 欧美成人第一页 |