Python函數(shù)裝飾器常見使用方法實例詳解
本文實例講述了Python函數(shù)裝飾器常見使用方法。分享給大家供大家參考,具體如下:
一、裝飾器
首先,我們要了解到什么是開放封閉式原則?
軟件一旦上線后,對修改源代碼是封閉的,對功能的擴張是開放的,所以我們應(yīng)該遵循開放封閉的原則。
也就是說:我們必須找到一種解決方案,能夠在不修改一個功能源代碼以及調(diào)用方式的前提下,為其加上新功能。
總結(jié):原則如下:
1、不修改源代碼
2、不修改調(diào)用方式
目的:在遵循1和2原則的基礎(chǔ)上擴展新功能。
二、什么是裝飾器?
器:指的是工具,
裝飾:指的是為被裝飾對象添加新功能。
完整的含義:裝飾器即在不修改裝飾對象源代碼與調(diào)用方式的前提下,為被裝飾器對象添加新功能的一種函數(shù),這個函數(shù)的特殊之處就在于它的返回值也是一個函數(shù)。
一般而言,我們想要拓展原來函數(shù)的代碼,直接的辦法就是侵入代碼里面修改,例如:
import time def index(): start_time=time.time() time.sleep(3) print('hello word') stop_time=time.time() print('run time is %s'%(stop_time-start_time)) index()
輸出:
hello word
run time is 3.000171422958374
以上代碼就是讓你過三秒才打印'hello word',下面我們要再添加一個新功能,和上面的功能一樣,但是要傳參數(shù)進去,過5秒輸出結(jié)果。
修改1:
import time def index(): time.sleep(3) print('hello word') def home(name): time.sleep(5) print('welcome %s to home page'%name) def wrapper(func): start_time=time.time() func('haolo') stop_time=time.time() print('run time is %s'%(stop_time-start_time)) wrapper(home)
輸出:
welcome haolo to home page
run time is 5.000286102294922
這樣寫感覺還是不怎么好,而且我們還修改了函數(shù)的調(diào)用方式,很不符合規(guī)矩。所以我們還是換一種方式來修改它。通過裝飾器的方式。
修改2
import time def index(): time.sleep(3) print('hello word') def home(name): time.sleep(5) print('welcome to %s'%name) def outter(func): # func為最原始的inde 和home def warpper(): start_time=time.time() func('yuan') stop_time=time.time() print(stop_time-start_time) return warpper home=outter(home) ###home這個變量名是新賦值的,把原來的home給覆蓋了。 home()
輸出:
welcome to yuan
5.000286102294922
這種方式雖然滿足了不修改源代碼和不修改調(diào)用方式的條件,但還是不能夠?qū)崿F(xiàn)兩個函數(shù)同時運行的功能,說到底還是不行,我們還得想個方式出來。就是讓他們兩個同時運行。這時,我又想到了上節(jié)課所學(xué)的知識,就是*args和**kargs,用兩個函數(shù)通過可變參數(shù)形式來實現(xiàn)內(nèi)嵌函數(shù)的形式傳入,所以它支持運行是構(gòu)建參數(shù)列表,這對于以上兩次不能解決的辦法是最有效的。下面我們來試試,看到底能不能成功。
方式3:
import time def index(): time.sleep(3) print('hello word') def home(name): time.sleep(5) print('welcome %s to home page'%name) def timmer(func): #func為最原始的home def warpper(*args,**kwargs): start_time=time.time() res=func(*args,**kwargs) #調(diào)用了最原始的home stop_time=time.time() print(stop_time-start_time) return res return warpper index=timmer(index) #為最新的index = wrapper home=timmer(home) #為最新的home = wrapper home(name='yuan') #wrapper=('yuan') index() #wrapper
輸出:
welcome yuan to home page
5.000285863876343
hello word
3.000171661376953
看吧,很快就實現(xiàn)了兩個功能并用,而且我們還沒有修改原始代碼,還有調(diào)用方式。
其實很簡單,我只是用了一個無參裝飾器的模板,這個模板可以說是萬能的,在以后很多的函數(shù)代碼都可以用這種方式來套用。
模板:
def outer(func): def inner(*args,**kwargs): res=func(*args,**kwargs) return res return inner
現(xiàn)在又有問題來了,我們調(diào)裝飾器的時候,每調(diào)一次,又要把裝飾器對象傳進來,調(diào)一次又傳一次,這樣不會覺得很麻煩嗎?那么我們又想到了一種方法,就是裝飾器語法糖,在被裝飾對象的上面加@timmer
用它來取代 index=timmer(index)
并且把返回值正常的返回給它。
import time def timmer(func): #func為最原始的home def warpper(*args,**kwargs): start_time=time.time() res=func(*args,**kwargs) #調(diào)用了最原始的home stop_time=time.time() print(stop_time-start_time) return res return warpper @timmer #就是取代底下的 index=timmer(index) def index(): time.sleep(3) print('hello word') @timmer #就是取代底下的home=timmer(home) home(name='yuan') def home(name): time.sleep(5) print('welcome %s to home page'%name) index() home('liuyuan')
輸出:
hello word
3.000171661376953
welcome liuyuan to home page
5.000286102294922
注意:這里的timmer函數(shù)就是最原始的裝飾器,它的參數(shù)就是一個函數(shù),然后返回值也是一個函數(shù)。其中作為參數(shù)的這個函數(shù)index()
和hemo(name)
就是在返回函數(shù)的wrapper()
的內(nèi)部執(zhí)行。然后再這兩個函數(shù)的前面加上@timmer
,index()
和home(name)
函數(shù)就相當于被注入了計時功能,現(xiàn)在只需要調(diào)用index()
和home('yuan')
,它就已經(jīng)變身為'新功能更多的函數(shù)了。'
所以這里的裝飾器就像一個注入的符號:有了它,拓展了原來函數(shù)的功能既不需要侵入函數(shù)內(nèi)更改代碼,也不需要重復(fù)執(zhí)行原函數(shù)。
用裝飾器來實現(xiàn)認證功能:
import time current_user={ 'username':None, #'login_time':None } def auth(func): # func = index def wrapper(*args,**kwargs): if current_user['username']: print('已經(jīng)登錄過了') res=func(*args,**kwargs) return res uname = input('輸入用戶名:').strip() pwd = input('密碼:').strip() if uname == 'yuan' and pwd == '123': print('登錄成功') current_user['username']=uname res = func(*args,**kwargs) return res else: print('用戶名或密碼錯誤') return wrapper @auth #index = auth(index) def index(): time.sleep(1) print('welcom to index page') @auth def home(name): time.sleep(2) print('welcome %s to home page'%name) input() home('yuan')
有參數(shù)的裝飾器來用于用戶認證
import time current_user={ 'username':None, # 'login_time':None } def auth(func): # func=index def wrapper(*args,**kwargs): if current_user['username']: print('已經(jīng)登陸過了') res=func(*args,**kwargs) return res uname=input('用戶名>>: ').strip() pwd=input('密碼>>: ').strip() if uname == 'yuan' and pwd == '123': print('登陸成功') current_user['username']=uname res=func(*args,**kwargs) return res else: print('用戶名或密碼錯誤') return wrapper def timmer(func): def wrapper(*args,**kwargs): start_time=time.time() res=func(*args,**kwargs) stop_time=time.time() print(stop_time-start_time) return res return wrapper @timmer # timmer 統(tǒng)計的是auth+index的執(zhí)行時間 @auth def index(): time.sleep(1) print('welcome to index page') return 122 index()
疊加多個裝飾器:
import time current_user={ 'username':None, # 'login_time':None } def auth(func): # func=index def wrapper(*args,**kwargs): if current_user['username']: print('已經(jīng)登陸過了') res=func(*args,**kwargs) return res uname=input('用戶名>>: ').strip() pwd=input('密碼>>: ').strip() if uname == 'egon' and pwd == '123': print('登陸成功') current_user['username']=uname res=func(*args,**kwargs) return res else: print('用戶名或密碼錯誤') return wrapper def timmer(func): def wrapper(*args,**kwargs): start_time=time.time() res=func(*args,**kwargs) stop_time=time.time() print(stop_time-start_time) return res return wrapper @timmer # timmer 統(tǒng)計的是auth+index的執(zhí)行時間 @auth def index(): time.sleep(1) print('welcome to index page') return 122 index()
關(guān)于Python相關(guān)內(nèi)容感興趣的讀者可查看本站專題:《Python函數(shù)使用技巧總結(jié)》、《Python面向?qū)ο蟪绦蛟O(shè)計入門與進階教程》、《Python數(shù)據(jù)結(jié)構(gòu)與算法教程》、《Python字符串操作技巧匯總》、《Python編碼操作技巧總結(jié)》及《Python入門與進階經(jīng)典教程》
希望本文所述對大家Python程序設(shè)計有所幫助。
相關(guān)文章
python閉包、深淺拷貝、垃圾回收、with語句知識點匯總
在本篇文章里小編給大家整理了關(guān)于python閉包、深淺拷貝、垃圾回收、with語句知識點匯總,有興趣的朋友們學(xué)習(xí)下。2020-03-03Python Numpy教程之排序,搜索和計數(shù)詳解
這篇文章主要為大家詳細介紹了Python?NumPy中排序,搜索和計數(shù)的實現(xiàn),文中的示例代碼講解詳細,對我們學(xué)習(xí)Python有一定幫助,需要的可以參考一下2022-08-08