生活随笔
收集整理的這篇文章主要介紹了
Python参数类型
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
位置參數(shù)默認(rèn)參數(shù)可變參數(shù)命名關(guān)鍵字參數(shù)關(guān)鍵字參數(shù) 1 def position_only(a, b):
2 print(a, b)
3
4 def keyword(a=
'a', b=
'b'):
5 print(a, b)
6
7 def arg(a, *
args):
8 print(a, args)
9
10 def kw(a, **
kwargs):
11 print(a, kwargs)
12
13 def many1(a, b, c=
'c', *args, d=
'd', e=
'e', **
kwargs):
14 print(a, b, c, args, d, e, kwargs)
15
16 def many2(a, b=
'b', c=
'c', *, d=
'd', e=
'e', **
kwargs):
17 print(a, b, c, d, e, kwargs)
18
19 if __name__ ==
'__main__':
20 position_only(
'a',
'b')
21 keyword()
22 keyword(
'b',
'a')
23 keyword(b=
'a', a=
'b')
24 arg(
'a',
'b',
'c',
'd',
'e')
25 kw(
'a', b=
'b', c=
'c')
26 many1(
'a',
'b',
'c', e=
'E', d=
'D', f=
'f', g=
'g')
27 many2(
'a',
'B',
'C', f=
'f', g=
'g')
運(yùn)行結(jié)果為:
a b
a b
b a
b a
a ('b',
'c',
'd',
'e')
a {'b':
'b',
'c':
'c'}
a b c () D E {'f':
'f',
'g':
'g'}
a B C d e {'f':
'f',
'g':
'g'}
因此:
位置參數(shù)按參數(shù)位置依次傳遞引用,若傳入?yún)?shù)個(gè)數(shù)不符,則提示錯(cuò)誤。默認(rèn)參數(shù)與位置參數(shù)類似,但可以指定變量名(此時(shí)可以不按順序傳入數(shù)據(jù)),若傳入數(shù)據(jù)少于參數(shù)個(gè)數(shù),則使用默認(rèn)值。可變參數(shù)用于處理傳入數(shù)據(jù)多于參數(shù)個(gè)數(shù)的情況,默認(rèn)將多余數(shù)據(jù)存入元組args。命名關(guān)鍵字參數(shù)用于傳入鍵值對(duì),它與默認(rèn)參數(shù)類似,但差別在于無法通過位置自動(dòng)傳入數(shù)據(jù)。關(guān)鍵字參數(shù)用于處理傳入鍵值對(duì)不屬于默認(rèn)參數(shù)和關(guān)鍵字參數(shù)的情況,默認(rèn)將多余鍵值對(duì)存入字典kwargs。注意:
傳入?yún)?shù)的順序必須為1-5,若*args不存在,可加入*參數(shù),以區(qū)分默認(rèn)參數(shù)和命名關(guān)鍵字參數(shù)。
?
轉(zhuǎn)載于:https://www.cnblogs.com/lyg-blog/p/8798967.html
總結(jié)
以上是生活随笔為你收集整理的Python参数类型的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。