第一節(jié) 總覽
Section I Overview
??It is well known that if a function defines a formal parameter, then the parameter must be passed when calling the function, otherwise the system will report an error.
??眾所周知,如果函數(shù)定義了形參,那么調(diào)用函數(shù)的時候就要傳遞參數(shù),否則系統(tǒng)將會報錯。
#正確的傳遞參數(shù)方式 The right way of passing parameters
In [34]: def ad(a,b):
...: print(a+b)
...:
In [35]: ad(1,2)
3
#錯誤的傳遞參數(shù)方式 The wrong way to pass parameters
In [34]: def ad(a,b):
...: print(a+b)
In [36]: ad(1)
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-36-e6dd8e29e4b8> in <module>()
----> 1 ad(1)
TypeError: ad() missing 1 required positional argument: 'b'
??再看如下兩個范例:
?? Look at the following two examples:
??我們在函數(shù)的參數(shù)中加入一個形為*args的參數(shù):
??We add a parameter in the form of * argsto the parameter of the function:
In [23]: def test(a,b,*args):
...: print(a)
...: print(b)
...: print(args)
In [24]: test(1,2)
1
2
()
In [25]: def test(a,b,*args):
...: print(a)
...: print(b)
...: print(args)
In [26]: test(1,2,3,4,5,6)
1
2
(3, 4, 5, 6)
??It can be seen that all the additional parameter functions are received and output in tuple mode. Since it is tuple, can we change the output mode?
??可見多出來的參數(shù)函數(shù)以元組方式全部接收并進(jìn)行了輸出,既然是元組,那我們是不是可以改變一下輸出方式呢?
In [37]: def test(a,b,*args):
...: print(a)
...: print(b)
...: for t in args:
...: print(t)
...:
In [38]: test(1,2,3,4,5,6)
1
2
3
4
5
6
??下面我們再增加一個形參,名為**kwargs:
??Let's add another parameter called ** kwargs:
In [39]: def test(a,b,*args,**kwargs):
...: print(a)
...: print(b)
...: print(args)
...: print(kwargs)
...:
In [41]: test(1,2)
1
2
()
{}
??在只傳遞了2個參數(shù)的情況下,可以看到第四個參數(shù)數(shù)據(jù)的類型是一個字典。
??With only two parameters passed, you can see that the type of the fourth parameter data is a dict.
??我們用剛才的方式來調(diào)用試試看:
??Let's try calling it the way we did just now:
In [42]: test(1,2,3,4,5,6)
1
2
(3, 4, 5, 6)
{}
??這時候我們必須要知道的就是如何才能把參數(shù)轉(zhuǎn)入字典中呢?
??Now what we have to know is how to put the parameters into the dict?
??看如下代碼:
??Look at the code below:
In [48]: test(1,2,3,4,5,6,7,a23=10,b8="1")
1
2
(3, 4, 5, 6, 7)
{'a23': 10, 'b8': '1'}
??現(xiàn)在可以得知,要傳遞參數(shù)到字典中,參數(shù)必須滿足XX=XX的模式:
??Now you can see that in order to pass parameters to the dict, the parameters must satisfy the mode XX = XX.
第二節(jié) *args 的解包
Section 2 * Args unpacking
??上節(jié)說到,只要在調(diào)用函數(shù)的時候,不傳遞帶key的參數(shù),那所有的參數(shù)都將存入到*args中以元組方式返回。
??As mentioned in the previous section, as long as the parameters with key are not passed when the function is called, all the parameters will be stored in *args and returned as tuples.
??那我們在上面函數(shù)定義的代碼中稍作改動,讓函數(shù)在輸出 *args 的同時,把 *args 中元素的個數(shù)打印出來。
??So let's make a slight change in the code defined by the function above so that the function prints out the number of elements in * args at the same time as it outputs * args.
In [81]: def test(a,b,*args,**kwargs):
...: print(a)
...: print(b)
...: print(args,end='')
...: print("-----*args中元素的個數(shù)為:"+str(len(args)))
...: print(kwargs)
...:
In [82]: test(1,2,3,4,5,6,7,8,9)
1
2
(3, 4, 5, 6, 7, 8, 9)-----*args中元素的個數(shù)為:7
{}
??我們把函數(shù)調(diào)用的代碼作一丟丟的改動,再來看輸出的情況:
??Let's make a little change to the code of the function call, and then look at the output.
In [83]: test(1,2,(3,4,5,6,7,8,9))
1
2
((3, 4, 5, 6, 7, 8, 9),)-----*args中元素的個數(shù)為:1
{}
??注意到哪里不同了嗎?對,僅僅是加了一對括號()而已。
??Notice what's different? Yes, just a pair of parentheses().
??很好,到這里我們看到了兩次“相互對應(yīng)”的操作,我們調(diào)用時傳遞了7個參數(shù),返回就是7個參數(shù)。我們調(diào)用時傳遞了1個參數(shù),返回的也是一個參數(shù)。
??Well, here we see two "corresponding" operations. We pass seven parameters when we call, seven parameters when we return, one parameter when we call, and one parameter when we return.
??但是不要忘了,我們是人類,人類是很懶惰的,所以我們想要做的事情就是:我傳遞剛才的1個參數(shù)給你,但是你要分開來返回給我,因?yàn)槟闶怯嬎銠C(jī),你要多做一點(diǎn)事情。
??But don't forget, we are human beings who are very lazy, so what we want to do is: I pass you a parameter just now, but you have to separate and back it to me, because you are a computer, you have to do more jobs.
??什么都不說,就是干!
??we will say we will do!
In [84]: test(1,2,*(3,4,5,6,7,8,9))
1
2
(3, 4, 5, 6, 7, 8, 9)-----*args中元素的個數(shù)為:7
{}
In [85]:
??哈哈哈,這是不是非常懶,只加了一個*而已!整存零??!
??How lazy we are!Only one *was added.Integral storage and zero fetch.
?? 這就是解包的含義!
?? That's what unpacking means!
??那么我們依葫蘆畫瓢,再簡單看一下dict的解包是什么樣子。首先還是要簡單修改一下代碼,輸出一下dict的元素的個數(shù)。
??That's what unpacking means! So let's draw a gourd and see what dict's unpacking looks like. First, we need to simply modify the code and output the number of dictelements.
In [85]: def test(a,b,*args,**kwargs):
...: print(a)
...: print(b)
...: print(args,end='')
...: print("-----*args中元素的個數(shù)為:"+str(len(args)))
...: print(kwargs,end='')
...: print("-----**kwargs中元素的個數(shù)為:"+str(len(kwargs)))
...:
In [86]: test(1,2,3,4,5,6,7,8,9,a1=1,a2=2,a3=3)
1
2
(3, 4, 5, 6, 7, 8, 9)-----*args中元素的個數(shù)為:7
{'a1': 1, 'a2': 2, 'a3': 3}-----**kwargs中元素的個數(shù)為:3
??現(xiàn)在我們把三個鍵值對打包看一下,對,應(yīng)該很簡單,就是像剛才那么操作,把后面三對參數(shù)用{}括起來,走起!
??Now let's take a look at the three key pairs packaged together. Yes, it should be very simple. Just like what we did just now, we can wrap up the last three pairs of parameters with {},let's go!
In [87]: test(1,2,3,4,5,6,7,8,9,{a1=1,a2=2,a3=3})
File "<ipython-input-87-879379c68e42>", line 1
test(1,2,3,4,5,6,7,8,9,{a1=1,a2=2,a3=3})
^
SyntaxError: invalid syntax
??注意看提示,錯誤的語法....。仔細(xì)一看,對哦,字典內(nèi)元素的格式應(yīng)該是XX:XX才對!立刻改之!
??Pay attention to the hints, invalid syntax... Look carefully, yeah, the format of the elements in the dict should be XX:XX. Change it immediately!
In [88]: test(1,2,3,4,5,6,7,8,9,{a1:1,a2:2,a3:3})
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
<ipython-input-88-3cd0045c1bff> in <module>()
----> 1 test(1,2,3,4,5,6,7,8,9,{a1:1,a2:2,a3:3})
NameError: name 'a1' is not defined
??神馬情況?怎么又出錯了?再看提示,a1沒有定義!
??What's wrong? Look at the hint , a1 is not defined!
??現(xiàn)在我們仔細(xì)看上上圖正確運(yùn)行的輸出,發(fā)現(xiàn)神馬沒有?
??Now let's take a closer look at the previous output that worked correctly, and find out what?
??對的!上上圖的a1、a2、a3已經(jīng)被解讀為了字符串' ',而剛才的代碼a1被識別為了變量,而且變量沒有定義,自然就報錯了。那么我們繼續(xù)來更正這個錯誤好了,把a1、a2、a3全部改為字符串類型。
??Right! The a1、a2、a3of the above figure have been interpreted as strings ' ',while the code a1 just now is interpreted as a variable, and the variable is undefined, so the error will occur. So let's go ahead and correct this mistake. Changea1、a2、a3 all to string.
In [89]: test(1,2,3,4,5,6,7,8,9,{'a1':1,'a2':2,'a3':3})
1
2
(3, 4, 5, 6, 7, 8, 9, {'a1': 1, 'a2': 2, 'a3': 3})-----*args中元素的個數(shù)為:8
{}-----**kwargs中元素的個數(shù)為:0
??這次結(jié)果好像沒有報錯唉!打包應(yīng)該是已經(jīng)成功了。咦,但是好像還是有一點(diǎn)超出預(yù)期。
??There seems to be no mistake in this result. Packing should have been successful. Gee, but it still seems a little out of expectations.
??我們回憶一下剛才元組的情況,我用()把幾個參數(shù)括了起來,這個參數(shù)包就被*args接收了,那我把鍵值對用{}括起來了,應(yīng)該是被**kwargs接收才對?。?br>
??Let's recall the tuple case just now. I encapsulated several parameters with () and the parameter package was received by *args. Then I encapsulated the key-value pairs with {}, which should be received by **kwargs.
??是不是感覺好有道理,又沒有什么證據(jù)的感覺^_^!
??Does it make sense to feel good ?
??**kwargs是什么類型?是dict,那就是鍵和值要成對的出現(xiàn)才行。
??What is the type of **kwargs? It's dict. That's where keys and values appear in pairs.
??我們把字典中的鍵key和值value比作一雙手套的左右兩只,然后再考慮這么一個例子:
??We compare the keys keyand value in the dictionary to the left and right of a pair of gloves, and then consider such an example:
- 你是我的好朋友。
- You are my best friend.
- 有一天你被蜘蛛咬了,長出了六只手,結(jié)果到了冬天太冷了,你卻不敢出門買手套,于是打發(fā)我去幫你買。
- One day you were bitten by a spider and grew six hands. As a result, it was too cold in winter and you dared not go out to buy gloves. So you sent me to buy Gloves for you
- 人生苦短,我用python。額不,我要和你開個玩笑。于是我把買來的三雙手套,鎖在了一個鐵盒子里,交給了你。
- Life is short. I use python. No, I'm kidding you. So I locked the three pairs of gloves I bought in an iron box and gave them to you.
- 親愛的蜘蛛俠你,瞬間滿怒氣,開啟狂暴怒吼:“賤人!我要的是手套!”
- Dear Spider-Man you, instantly full of anger, open the rage roar: "Bitch! I want gloves!"
- 我:“親愛的,這是手套lol 在盒子里呢lol”
- Me: "Honey, this is glove in the box."
- 你:“TMD 駝你是他可已經(jīng)西去了,我馬上就會火,打開快點(diǎn)的,以后跟哥混,妹子少不了”
- Iron Man is dead, I will be famous soon.Open it now! If you work for me in the future, I will make you rich, rich and enjoyable. Wives and concubines will flock together.
-我: 好嘞,客官您里屋請,立馬開!(此處省略......BYTE)。咋樣,合適不? - Okay, wait a moment. How's it going? Are you satisfied?
- 你:好使!
- Fucking good!
okok,我知道太長了又啰嗦,看不懂是吧,好的我們接下來翻譯一下:
- 你
**kwargs是我的好朋友。 - 有一天你被蜘蛛咬了,長出了六只手
key:value,key:value,key:value,結(jié)果到了冬天太冷了,你卻不敢出門買手套a1':1,'a2':2,'a3':3,于是打發(fā)我去幫你買。 - 人生苦短,我用python。額不,我要和你開個玩笑。于是我把買來的三雙手套
a1':1,'a2':2,'a3':3,鎖在了一個鐵盒子里{a1':1,'a2':2,'a3':3},交給了你。 - 親愛的蜘蛛俠你,瞬間滿怒氣,開啟狂暴怒吼:“賤人!我要的是手套
a1':1,'a2':2,'a3':3!” - 我:“親愛的,這是手套
a1':1,'a2':2,'a3':3lol 在盒子里呢{a1':1,'a2':2,'a3':3}lol” - 你:“TMD 駝你是他可已經(jīng)西去了,我馬上就會火,打開快點(diǎn)的,以后跟哥混,妹子少不了”
- 我: 好嘞,客官您里屋請,立馬開
**{a1':1,'a2':2,'a3':3}!(此處省略......BYTE)。咋樣,合適不? - 你:好使!
a1':1,'a2':2,'a3':3
In [85]: def test(a,b,*args,**kwargs):
...: print(a)
...: print(b)
...: print(args,end='')
...: print("-----*args中元素的個數(shù)為:"+str(len(args)))
...: print(kwargs,end='')
...: print("-----*kwargs中元素的個數(shù)為:"+str(len(kwargs)))
In [90]: test(1,2,3,4,5,6,7,8,9,**{'a1':1,'a2':2,'a3':3})
1
2
(3, 4, 5, 6, 7, 8, 9)-----*args中元素的個數(shù)為:7
{'a1': 1, 'a2': 2, 'a3': 3}-----*kwargs中元素的個數(shù)為:3
大招就是:**{ }
肚子餓,吃飯去了。