如何實現(xiàn)一個python函數(shù)裝飾器(Decorator)
裝飾器本質(zhì)上是一個 Python 函數(shù)或類,它可以讓其他函數(shù)或類在不需要做任何代碼修改的前提下增加額外功能,裝飾器的返回值也是一個函數(shù)/類對象。它經(jīng)常用于為已有函數(shù)/類添加記錄日志、計時統(tǒng)計、性能測試等。
首先定義一個倒計時函數(shù),這個函數(shù)的功能非常簡單,就是把n從當(dāng)前值減少到0。
def countdown(n): while n > 0: print(’time’ + str(n)) n -= 1print(countdown.__name__)
程序輸出:
countdown
1.為函數(shù)增加一個日志裝飾器
假設(shè)現(xiàn)在要增強countdown的功能,在函數(shù)調(diào)用前后自動打印日志,又不想修改函數(shù)自身的功能。這種在代碼運行期間動態(tài)增加功能的方式,稱之為裝飾器(Decorator)。
能打印日志的decorator,可以定義如下:
def log(func): def wrapper(*args, **kw): print(’call %s().’ % func.__name__) return func(*args, **kw) return wrapper
然后我們借助Python的@語法,把decorator置于函數(shù)的定義處:
@logdef countdown(n): while n > 0: print(’time:’ + str(n)) n -= 1countdown(10)
程序輸出:
call countdown().time:10time:9time:8time:7time:6time:5time:4time:3time:2time:1
但此時我們再打印函數(shù)的name:
print(countdown.__name__)
程序輸出:
wrapper
我們發(fā)現(xiàn)函數(shù)的元數(shù)據(jù)信息變了,這顯然不是我們想要的結(jié)果。
2. 在裝飾器中拷貝元數(shù)據(jù)
為了把函數(shù)的元數(shù)據(jù)信息都保留下來,我們可以直接使用Python提供的functools庫中的@wraps裝飾器。
from functools import wrapsdef log(func): @wraps(func) def wrapper(*args, **kw): print(’call %s().’ % func.__name__) return func(*args, **kw) return wrapper@logdef countdown(n): while n > 0: print(’time:’ + str(n)) n -= 1print(countdown.__name__)
程序輸出:
countdown
3.為函數(shù)增加一個計時裝飾器
添加函數(shù)裝飾器的方法已經(jīng)講清楚了,現(xiàn)在再實現(xiàn)一個完整的函數(shù)計時耗時裝飾器。
import timefrom functools import wrapsdef TimeCost(func): @wraps(func) def wrapper(*arg, **kwargs): start = time.time() result = func(*args, **kwargs) end = time.time() print(func.__name__, end - start) return result return wrapper@TimeCostdef countdown(n): while n > 0: print(’time:’ + str(n)) n -= 1countdown(10000)
函數(shù)輸出:
(’countdown’, 0.0004801750183105469)
參考資料:
https://www.liaoxuefeng.com/wiki/1016959663602400/1017451662295584
Python Cookbook中文版
以上就是如何實現(xiàn)一個python函數(shù)裝飾器(Decorator)的詳細(xì)內(nèi)容,更多關(guān)于python函數(shù)裝飾器的資料請關(guān)注好吧啦網(wǎng)其它相關(guān)文章!
相關(guān)文章:
1. ASP動態(tài)網(wǎng)頁制作技術(shù)經(jīng)驗分享2. msxml3.dll 錯誤 800c0019 系統(tǒng)錯誤:-2146697191解決方法3. ASP中if語句、select 、while循環(huán)的使用方法4. xml中的空格之完全解說5. WMLScript的語法基礎(chǔ)6. 匹配模式 - XSL教程 - 47. XML入門的常見問題(四)8. ASP中解決“對象關(guān)閉時,不允許操作。”的詭異問題……9. html小技巧之td,div標(biāo)簽里內(nèi)容不換行10. 解決ASP中http狀態(tài)跳轉(zhuǎn)返回錯誤頁的問題
