日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學無先后,達者為師

網站首頁 編程語言 正文

python函數裝飾器構造和參數傳遞_python

作者:python老鳥 ? 更新時間: 2022-05-08 編程語言

前言:

通過@語句調用一個函數去給另一個函數增加或修改一些功能的語法規則稱之為Python裝飾器。下面通過一個小案例來簡單的理解什么是裝飾器。

def dog():
? ? print('搖尾巴')
? ? def cat():
? ? ? ? print('喵喵喵')
? ? ? ??
call = '狗'if call == '狗':
? ? dog()else:
? ? cat()

這時候有一個需求,必須是貓和狗的主人呼喊它們才會做出以上動作,就需要對指令發出者進行身份驗證。如果直接在判斷上采用身份驗證,這樣代碼重用度會很低,如果在上面兩個函數中寫,如果驗證代碼過多,可能需要寫好幾遍。這時候我們可以再創建一個函數,在調用dogcat函數的時候先調用身份驗證函數,但是這樣,我們的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函數,所以先執行身份驗證,然后又調用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()

函數體不發生改變,增加了額外的功能,重用性高。 裝飾器內部必須使用閉包函數,否則當使用@時,裝飾器就會被直接執行,注意執行順序。

三. python裝飾器疊加

# 裝飾器可以被疊加使用
def func(f):
? ? def test():
? ? ? ? print('主人身份驗證')
? ? ? ? f()
? ? return test
? ??
def func2(f):
? ? def test2():
? ? ? ? print('=======')
? ? ? ? f()
?return test2
?
@func2
@func ?# 可以疊加使用裝飾器,先執行上面的裝飾器
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)的執行結果就是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))

原文鏈接:https://blog.csdn.net/weixin_48728769/article/details/121752792

欄目分類
最近更新