python中的decorator的作用詳解
1、概念
裝飾器(decorator)就是:定義了一個函數(shù),想在運行時動態(tài)增加功能,又不想改動函數(shù)本身的代碼??梢云鸬綇陀么a的功能,避免每個函數(shù)重復性編寫代碼,簡言之就是拓展原來函數(shù)功能的一種函數(shù)。在python中,裝飾器(decorator)分為 函數(shù)裝飾器 和 類裝飾器 兩種。python中內置的@語言就是為了簡化裝飾器調用。
列出幾個裝飾器函數(shù):
打印日志:@log
檢測性能:@performance
數(shù)據(jù)庫事務:@transaction
URL路由:@post('/register')
2、使用方法
(1)無參數(shù)decorator
編寫一個@performance,它可以打印出函數(shù)調用的時間。
import time def performance(f): def log_time(x): t1 = time.time() res = f(x) t2 = time.time() print 'call %s() in %fs' %(f.__name__,(t2 - t1)) return res return log_time @performance def factorial(n): return reduce(lambda x,y : x*y,range(1,n+1)) print factorial(10)
運行結果:
call factorial() in 0.006009s 2 3628800
運行原理:
此時,factorial就作為performance的函數(shù)對象,傳遞給f。當調用factorial(10)的時候也就是調用log_time(10)函數(shù),而在log_time函數(shù)內部,又調用了f,這就造成了裝飾器的效果。說明f是被裝飾函數(shù),而x是被裝飾函數(shù)的參數(shù)。
(2)帶參數(shù)decorator
請給 @performace 增加一個參數(shù),允許傳入's'或'ms'。
import time def performance(unit): def perf_decorator(f): def wrapper(*args, **kw): t1 = time.time() r = f(*args, **kw) t2 = time.time() t = (t2 - t1)*1000 if unit =='ms' else (t2 - t1) print 'call %s() in %f %s'%(f.__name__, t, unit) return r return wrapper return perf_decorator @performance('ms') def factorial(n): return reduce(lambda x,y: x*y, range(1, n+1)) print factorial(10)
運行結果:
call factorial() in 9.381056 ms 2 3628800
運行原理:
它的內部邏輯為factorial=performance('ms')(factorial);
這里面performance('ms')返回是perf_decorator函數(shù)對象,performance('ms')(factorial)其實就是perf_decorator(factorial),然后其余的就和上面是一樣的道理了。
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關文章
Python實現(xiàn)從log日志中提取ip的方法【正則提取】
這篇文章主要介紹了Python實現(xiàn)從log日志中提取ip的方法,涉及Python文件讀取、數(shù)據(jù)遍歷、正則匹配等相關操作技巧,需要的朋友可以參考下2018-03-03