python中*args與**kwarsg及閉包和裝飾器的用法
*args與**kwarsg及閉包和裝飾器
過(guò)程
先理解閉包,再理解裝飾器,不要忘了不定長(zhǎng)參數(shù)
def func(): msg = '111' def func1(): print(msg) return func1 """ 1-理解閉包 閉包即內(nèi)部函數(shù)調(diào)用外部函數(shù)作用域里面的變量 比如func1就是一個(gè)閉包函數(shù) """ func()()# 這里實(shí)際上是func1()
""" 2-裝飾器 fn是被裝飾的目標(biāo)函數(shù) 2.1-僅僅只是傳遞函數(shù)名的裝飾器[基本不會(huì)用到] 2.2-裝飾帶有參數(shù)的函數(shù) 2.3-裝飾帶有返回值的函數(shù) 2.4-裝飾參數(shù)不確定的函數(shù)[可歸類(lèi)到裝飾帶有參數(shù)的函數(shù)里面] 2.5-裝飾器本身攜帶參數(shù) """
def decorator(fn): def wrapper(): print("添加的功能,裝飾不帶有參數(shù)的函數(shù)") return fn() return wrapper @decorator def test(): print("原有功能") test()# 實(shí)際上是decorator(test) def decorator1(fn): def wrapper(n1,n2): print("添加的功能,裝飾帶有參數(shù)的函數(shù)") return fn(n1,n2) return wrapper @decorator1 def test1(a,b): print("a+b=%s"%(a+b)) print("原有功能") test1(1,2)# 實(shí)際上是decorator1(test1(1,2)) def decoretor2(fn): def wrapper(): print("添加的功能,裝飾帶有返回值的函數(shù)") res = fn() return res return wrapper @decoretor2 def test2(): print("原有功能") return "返回值001" a = test2() # 實(shí)際是decorator2(test2) print(a) def decorator3(fn): def warpper(*args,**kwargs): print("添加的功能,裝飾不定長(zhǎng)參數(shù)的函數(shù)") return fn(*args,**kwargs) return warpper @decorator3 def test3(n1,n2,n3): print("原有功能") print(n1+n2+n3) test3(1,2,3)# 實(shí)際上是decorator1(test1(1,2,3)) def decorator4(home): def func_1(fn): def wrapper(*args,**kwargs): print("裝飾器本身攜帶參數(shù)") print("目前家在%s"%(home)) return fn(*args,**kwargs) return wrapper return func_1 @decorator4(home='wuhan') def test4(n1,n2,n3): print("原有功能") print(n1+n2+n3) # test3(1,2,3)=decorator3(home="武漢")(test(1,2,3))() """ 1-先調(diào)用decorator3(home="wuhan") 2-執(zhí)行func_1(test(1,2,3)) # 到這里其實(shí)就和前面的裝飾器一樣 3-執(zhí)行wrapper 4-執(zhí)行test(1,2,3) """ test4(1,2,3)
Python fun(*args,**kwargs)中*args,**kwargs參數(shù)含義及用法
1. Python函數(shù)中的兩種參數(shù)
我們知道,在Python中有兩種參數(shù)
- 位置參數(shù)(positional argument): 位置參數(shù)只能由參數(shù)位置決定
- 關(guān)鍵詞參數(shù)(keyword argument): 關(guān)鍵詞參數(shù)只需要用 keyword = somekey 的方法即可傳參
位置參數(shù)只能由參數(shù)位置決定。這也就決定了位置參數(shù)一定要在前面,否則關(guān)鍵詞參數(shù)數(shù)量的變化都會(huì)使得位置無(wú)法判斷。
2. 理解函數(shù)調(diào)用中的*
*的作用是將tuple或者list中的元素進(jìn)行unpack,分開(kāi)傳入,作為多個(gè)參數(shù)。
def func(a,b,c) ?? ?print(a,b,c) alist = [1,2,3] # 這里alist的長(zhǎng)度必須和函數(shù)中參數(shù)的個(gè)數(shù)相同,否則會(huì)報(bào)錯(cuò) func(*alist) ?? ?# 等同于 func(1, 2, 3) 1 2 3
2.1 * 做了什么
它拆開(kāi)數(shù)列alist的數(shù)值作為位置參數(shù),并把這些位置參數(shù)傳給函數(shù)func來(lái)調(diào)用。
因此拆數(shù)列、傳位置參數(shù)意味著func(*alist)與func(1,2,3)是等效的,因?yàn)?alist= [1,2,3]。
3. 理解函數(shù)調(diào)用中的**
**的作用是unpack字典,并將字典中的數(shù)據(jù)項(xiàng)作為鍵值參數(shù)傳給函數(shù)。
為了更好的理解舉幾個(gè)例子:
def func(a, b, c): ? ? print(a, b, c) ? ?? if __name__ == "__main__": ? ? dic = {'b': 2, 'c': 3} ? ? func(1, b=2, c=3) ? ? func(1, **dic) 1 2 3 1 2 3
4. 理解函數(shù)調(diào)用中的*args和**kwargs
kwargs是keyword argument的縮寫(xiě),args就是argument。常見(jiàn)的是*args 在 **kwargs 前面。
這兩個(gè)的用途和效果如下:
def this_fun(a,b,*args,**kwargs): ?? ?""" ?? ?在這個(gè)函數(shù)定義中,參數(shù)”a, b”代表”常規(guī)參數(shù)列表”。 ?? ?args 接收元組作為位置參數(shù),而非是常見(jiàn)的參數(shù)列表 ?? ? ?? ?""" ? ? print(a,b) ? ? print(args) ? ? print(kwargs) if __name__ = '__main__' ?? ?this_fun(0,1,2,3,index1=11,index2=22) ?? ? 0,1 (2, 3) {'index2': 22, 'index1': 11}
也就是說(shuō),第一中不定的參數(shù)形式把剩下的沒(méi)有關(guān)鍵字的參數(shù)收起來(lái)形成一個(gè)tuple,而第二種把有關(guān)鍵字的收起來(lái)做成一個(gè)字典。
5. 實(shí)例說(shuō)明args, kwargs的應(yīng)用場(chǎng)景
5.1 子類(lèi)傳參給父類(lèi)方法
在任何時(shí)候繼承類(lèi)和重寫(xiě)方法的,我們應(yīng)當(dāng)用到args, kwargs將接收到的位置參數(shù)和鍵值參數(shù)給父類(lèi)方法。通過(guò)實(shí)例我們更好的理解
class Model(object): ? ? def __init__(self, name): ? ? ? ? self.name = name ? ? def save(self, force_update=False, force_insert=False): ? ? ? ? if force_update and force_insert: ? ? ? ? ? ? raise ValueError("Cannot perform both operations") ? ? ? ? if force_update: ? ? ? ? ? ? print("Updated an existing record") ? ? ? ? if force_insert: ? ? ? ? ? ? print("Created a new record")
定義一個(gè)類(lèi),我們可以創(chuàng)建類(lèi)的對(duì)象,類(lèi)的對(duì)象有一個(gè)方法save().假設(shè)類(lèi)的對(duì)象可以通過(guò)save()方法保存到數(shù)據(jù)庫(kù)中。通過(guò)函數(shù)save()參數(shù)來(lái)決定是否在數(shù)據(jù)庫(kù)中創(chuàng)建一條記錄或者更新現(xiàn)存的記錄。
構(gòu)造一個(gè)新類(lèi),類(lèi)有Model的行為,但只有符合某些條件才會(huì)保存這個(gè)類(lèi)的對(duì)象。這個(gè)新類(lèi)繼承Model,重寫(xiě)Model的save()
class ChildModel(Model): ? ? def save(self, *args, **kwargs): ? ? ? ? if self.name == 'abcd': ? ? ? ? ? ? super(ChildModel, self).save(*args, **kwargs) ? ? ? ? else: ? ? ? ? ? ? return None
實(shí)際上對(duì)應(yīng)的保存動(dòng)作發(fā)生在’Model’的save方法中。所以我們調(diào)用子類(lèi)的的save()方法而非’Model’的方法.子類(lèi)ChildModel的save()接收任何父類(lèi)save()需要的參數(shù),并傳給父類(lèi)方法。因此,子類(lèi)save()方法參數(shù)列表中有*args和**kwargs,它們可以接收任意位置參數(shù)或鍵值參數(shù),常規(guī)參數(shù)列表除外。
下面創(chuàng)建ChildModel實(shí)體并調(diào)用save方法:
c=ChildModel('abcd') c.save(force_insert=True) c.save(force_update=True) # 結(jié)果 Created a new record Updated an existing record
這里傳參數(shù)給對(duì)象的save()方法。調(diào)用的是子類(lèi)的save(), 它接收一個(gè)包含關(guān)鍵字參數(shù)kwargs的字典。然后,它使用**將字典作為關(guān)鍵字參數(shù)unpack,然后將其傳遞給超類(lèi)save()。因此,超類(lèi)save()獲得關(guān)鍵字參數(shù)force_insert并執(zhí)行相應(yīng)的操作。
5.2 *args 實(shí)現(xiàn)sum
def my_sum(*args): ?? ?res = 0 ?? ?for val in args: ?? ??? ?res += val ?? ?return res ?? ? l1 = [4, 8] l2 = [1,2,3] print(my_sum(*l1)) ?? ??? ?# 12 print(my_sum(*l2)) ?? ??? ?# 6 print(my_sum(4,5,6)) ?? ?# 15
以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。
相關(guān)文章
Django跨域請(qǐng)求無(wú)法傳遞Cookie的解決
這篇文章主要介紹了Django跨域請(qǐng)求無(wú)法傳遞Cookie的解決方案,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2021-04-04python pygame實(shí)現(xiàn)五子棋小游戲
這篇文章主要為大家詳細(xì)介紹了python pygame實(shí)現(xiàn)五子棋小游戲,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2019-06-06基于Python pip用國(guó)內(nèi)鏡像下載的方法
今天小編就為大家分享一篇基于Python pip用國(guó)內(nèi)鏡像下載的方法。具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2018-06-06TensorFlow人工智能學(xué)習(xí)數(shù)據(jù)填充復(fù)制實(shí)現(xiàn)示例
這篇文章主要為大家介紹了TensorFlow人工智能學(xué)習(xí)如何進(jìn)行數(shù)據(jù)填充復(fù)制的實(shí)現(xiàn)示例,有需要的朋友可以借鑒參考下,希望能夠有所幫助2021-11-11Python網(wǎng)絡(luò)編程之使用TCP方式傳輸文件操作示例
這篇文章主要介紹了Python網(wǎng)絡(luò)編程之使用TCP方式傳輸文件操作,結(jié)合實(shí)例形式分析了使用socket模塊進(jìn)行tcp協(xié)議下文件傳輸?shù)脑硪约胺?wù)器端、客戶(hù)端相關(guān)實(shí)現(xiàn)技巧,需要的朋友可以參考下2019-11-11Python+Appium實(shí)現(xiàn)自動(dòng)化清理微信僵尸好友的方法
這篇文章主要介紹了Python+Appium實(shí)現(xiàn)自動(dòng)化清理微信僵尸好友的方法,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2021-02-02Python使用random和tertools模塊解一些經(jīng)典概率問(wèn)題
這篇文章主要介紹了Python使用random和tertools模塊解一些經(jīng)典概率問(wèn)題,本文講解了使用random和tertools模塊解羊車(chē)門(mén)問(wèn)題、撲克牌問(wèn)題、生日悖論等經(jīng)典概率問(wèn)題,需要的朋友可以參考下2015-01-01