本文實例講述了Python函數裝飾器常見使用方法。分享給大家供大家參考,具體如下:
一、裝飾器
首先,我們要了解到什么是開放封閉式原則?
軟件一旦上線后,對修改源代碼是封閉的,對功能的擴張是開放的,所以我們應該遵循開放封閉的原則。
也就是說:我們必須找到一種解決方案,能夠在不修改一個功能源代碼以及調用方式的前提下,為其加上新功能。
總結:原則如下:
1、不修改源代碼
2、不修改調用方式
目的:在遵循1和2原則的基礎上擴展新功能。
二、什么是裝飾器?
器:指的是工具,
裝飾:指的是為被裝飾對象添加新功能。
完整的含義:裝飾器即在不修改裝飾對象源代碼與調用方式的前提下,為被裝飾器對象添加新功能的一種函數,這個函數的特殊之處就在于它的返回值也是一個函數。
一般而言,我們想要拓展原來函數的代碼,直接的辦法就是侵入代碼里面修改,例如:
1
2
3
4
5
6
7
8
|
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',下面我們要再添加一個新功能,和上面的功能一樣,但是要傳參數進去,過5秒輸出結果。
修改1:
1
2
3
4
5
6
7
8
9
10
11
12
13
|
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
這樣寫感覺還是不怎么好,而且我們還修改了函數的調用方式,很不符合規矩。所以我們還是換一種方式來修改它。通過裝飾器的方式。
修改2
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
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
這種方式雖然滿足了不修改源代碼和不修改調用方式的條件,但還是不能夠實現兩個函數同時運行的功能,說到底還是不行,我們還得想個方式出來。就是讓他們兩個同時運行。這時,我又想到了上節課所學的知識,就是*args和**kargs,用兩個函數通過可變參數形式來實現內嵌函數的形式傳入,所以它支持運行是構建參數列表,這對于以上兩次不能解決的辦法是最有效的。下面我們來試試,看到底能不能成功。
方式3:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
|
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) #調用了最原始的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
看吧,很快就實現了兩個功能并用,而且我們還沒有修改原始代碼,還有調用方式。
其實很簡單,我只是用了一個無參裝飾器的模板,這個模板可以說是萬能的,在以后很多的函數代碼都可以用這種方式來套用。
模板:
1
2
3
4
5
|
def outer(func): def inner( * args, * * kwargs): res = func( * args, * * kwargs) return res return inner |
現在又有問題來了,我們調裝飾器的時候,每調一次,又要把裝飾器對象傳進來,調一次又傳一次,這樣不會覺得很麻煩嗎?那么我們又想到了一種方法,就是裝飾器語法糖,在被裝飾對象的上面加@timmer
用它來取代 index=timmer(index)
并且把返回值正常的返回給它。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
|
import time def timmer(func): #func為最原始的home def warpper( * args, * * kwargs): start_time = time.time() res = func( * args, * * kwargs) #調用了最原始的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函數就是最原始的裝飾器,它的參數就是一個函數,然后返回值也是一個函數。其中作為參數的這個函數index()
和hemo(name)
就是在返回函數的wrapper()
的內部執行。然后再這兩個函數的前面加上@timmer
,index()
和home(name)
函數就相當于被注入了計時功能,現在只需要調用index()
和home('yuan')
,它就已經變身為'新功能更多的函數了。'
所以這里的裝飾器就像一個注入的符號:有了它,拓展了原來函數的功能既不需要侵入函數內更改代碼,也不需要重復執行原函數。
用裝飾器來實現認證功能:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
|
import time current_user = { 'username' : None , #'login_time':None } def auth(func): # func = index def wrapper( * args, * * kwargs): if current_user[ 'username' ]: print ( '已經登錄過了' ) 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' ) |
有參數的裝飾器來用于用戶認證
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
|
import time current_user = { 'username' : None , # 'login_time':None } def auth(func): # func=index def wrapper( * args, * * kwargs): if current_user[ 'username' ]: print ( '已經登陸過了' ) 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 統計的是auth+index的執行時間 @auth def index(): time.sleep( 1 ) print ( 'welcome to index page' ) return 122 index() |
疊加多個裝飾器:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
|
import time current_user = { 'username' : None , # 'login_time':None } def auth(func): # func=index def wrapper( * args, * * kwargs): if current_user[ 'username' ]: print ( '已經登陸過了' ) 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 統計的是auth+index的執行時間 @auth def index(): time.sleep( 1 ) print ( 'welcome to index page' ) return 122 index() |
希望本文所述對大家Python程序設計有所幫助。
原文鏈接:https://www.cnblogs.com/lyox/p/8671098.html