python函數裝飾器構造和參數傳遞
前言:
通過@語句調用一個函數去給另一個函數增加或修改一些功能的語法規(guī)則稱之為Python裝飾器。下面通過一個小案例來簡單的理解什么是裝飾器。
def dog():
? ? print('搖尾巴')
? ? def cat():
? ? ? ? print('喵喵喵')
? ? ? ??
call = '狗'if call == '狗':
? ? dog()else:
? ? cat()這時候有一個需求,必須是貓和狗的主人呼喊它們才會做出以上動作,就需要對指令發(fā)出者進行身份驗證。如果直接在判斷上采用身份驗證,這樣代碼重用度會很低,如果在上面兩個函數中寫,如果驗證代碼過多,可能需要寫好幾遍。這時候我們可以再創(chuàng)建一個函數,在調用dog和cat函數的時候先調用身份驗證函數,但是這樣,我們的dog函數用在其他地方時如果不需要驗證就會有冗余代碼。上面幾種方案都有自己的缺點,我們可以試試前面學習的閉包函數來實現這個功能。
一.閉包函數
def func(f):
? ? def test():
? ? ? ? print('主人身份驗證')
? ? ? ? f()
? ? return test
? ??
def dog():
? ? print('搖尾巴')
dog = func(dog) # 這里的dog其實是test函數
?
def cat():
? ? print('喵喵喵')
cat = func(cat)
call = '狗'
if call == '狗':
? ? dog() # ★★★這里的dog函數其實是test函數,所以先執(zhí)行身份驗證,然后又調用f()函數,也就是原來的dog()函數,也可以給這行的dog函數換個名字,好理解★★★
else:
? ? cat()二.python裝飾器構造
python提供一種簡單的裝飾器寫法,叫做語法糖,
如下:
def func(f):
? ? def test():
? ? ? ? print('主人身份驗證')
? ? ? ? f()
? ? return test
? ??
@func
def dog():
? ? print('搖尾巴')
# dog = func(dog)
?
@func
def cat():
? ? print('喵喵喵')# cat = func(cat)
call = '狗'
if call == '狗':
? ? dog()
else:
? ? cat()函數體不發(fā)生改變,增加了額外的功能,重用性高。 裝飾器內部必須使用閉包函數,否則當使用@時,裝飾器就會被直接執(zhí)行,注意執(zhí)行順序。
三. python裝飾器疊加
# 裝飾器可以被疊加使用
def func(f):
? ? def test():
? ? ? ? print('主人身份驗證')
? ? ? ? f()
? ? return test
? ??
def func2(f):
? ? def test2():
? ? ? ? print('=======')
? ? ? ? f()
?return test2
?
@func2
@func ?# 可以疊加使用裝飾器,先執(zhí)行上面的裝飾器
def dog():
? ? print('搖尾巴')
dog() # 這里的dog函數其實是test和test2兩個函數,而test和test2又返回來調用上面的dog()原始函數四.python裝飾器傳參
1.裝飾器單個參數傳遞
def test(f):
? ? def test1(x):
? ? ? ? print('==========')
? ? ? ? f(x)
? ? return test1
? ??
@test
def func1(m):
? ? print(m)
? ??
func1(10)2.裝飾器多個參數傳遞
def test(f):
? ? def test1(x, y):
? ? ? ? print('==========')
? ? ? ? f(x, y)
? ? return test1
? ??
@test
def func2(m, n):
? ? print(m, n)
? ??
func2(10, 5)3.裝飾器的不定長參數
def test(f):
? ? def test1(*args, **kwargs):
? ? ? ? print('==========')
? ? ? ? f(*args, **kwargs)
? ? return test1
?
@test
def func2(a, b, c):
? ? # print(args, kwargs)
? ? print('*********')
func2(10, 5, c=6) # 這里的c和上面func2的第三個形參名要一致五、帶返回值的裝飾器
def test(f):
? ? def test1(*args, **kwargs): # 這里的test1函數要和被裝飾函數func2的結構保持一致
? ? ? ? print('==========')
? ? ? ? res = f(*args, **kwargs) # 這里相當于把被裝飾函數的結果拿過來賦值,f(*args, **kwargs)的執(zhí)行結果就是func2的返回值
? ? ? ? return res ?# 沒有返回值也可以這樣寫,返回結果就是None
? ? return test1
? ??
@test
def func2(a, b, c):
? ? # print(args, kwargs)
? ? print('*********')
? ? return a + b + c
print(func2(10, 5, c=88))到此這篇關于python函數裝飾器構造和參數傳遞的文章就介紹到這了,更多相關python函數裝飾器內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
詳解如何利用Pytest?Cache?Fixture實現測試結果緩存
這篇文章主要為大家詳細介紹了如何利用Pytest?Cache?Fixture實現測試結果緩存,文中的示例代碼講解詳細,感興趣的小伙伴可以跟隨小編一起了解一下2023-09-09
Python中的defaultdict與__missing__()使用介紹
下面這篇文章主要給大家介紹了關于Python中defaultdict使用的相關資料,文中通過示例代碼介紹的非常詳細,對大家學習或者使用python具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧。2018-02-02

