任意參數(shù) *
當(dāng)我們的函數(shù)接收參數(shù)為任意個(gè),或者不能確定參數(shù)個(gè)數(shù)時(shí),我們,可以利用
*
來(lái)定義任意數(shù)目的參數(shù),這個(gè)函數(shù)調(diào)用時(shí),其所有不匹配的位置參數(shù)會(huì)被賦值為元組,我們可以在函數(shù)利用循環(huán)或索引進(jìn)行使用
def
f
(
*
args
)
:
# 直接打印元組參數(shù)
print
(
args
)
print
(
'-'
*
20
)
# 循環(huán)打印元組參數(shù)
[
print
(
i
)
for
i
in
args
]
.
.
.
# 傳遞一個(gè)參數(shù)
f
(
1
)
print
(
'='
*
20
)
# 傳遞5個(gè)參數(shù)
f
(
1
,
2
,
3
,
4
,
5
)
示例結(jié)果:
(1,)
--------------------
1
====================
(1, 2, 3, 4, 5)
--------------------
1
2
3
4
5
###任意參數(shù) **
而
**
是用于收集關(guān)鍵字參數(shù)并將這些參數(shù)傳遞給一個(gè)新的字典,即在函數(shù)中我們可以利用處理字典的方式處理這些參數(shù)
def
f
(
**
args
)
:
# 直接打印字典參數(shù)
print
(
args
)
for
key
,
value
in
args
.
items
(
)
:
print
(
'{}: {}'
.
format
(
key
,
value
)
)
f
(
a
=
1
)
print
(
'='
*
20
)
f
(
a
=
1
,
b
=
2
,
c
=
3
)
示例結(jié)果:
{'a': 1}
a: 1
====================
{'a': 1, 'b': 2, 'c': 3}
a: 1
b: 2
c: 3
任意參數(shù)混合
我們可以混合一般參數(shù)、
*
參數(shù)以及
**
參數(shù)完成實(shí)現(xiàn)更加復(fù)雜的調(diào)用方式。
def
f
(
a
,
*
targs
,
**
dargs
)
:
print
(
a
,
targs
,
dargs
)
f
(
1
,
2
,
3
,
x
=
1
,
y
=
2
)
示例結(jié)果:
1 (2, 3) {'x': 1, 'y': 2}
可以看到這種調(diào)用方式并不那么直觀,甚至有些“混淆視聽(tīng)”,那么怎么在復(fù)雜任意參數(shù)的調(diào)用時(shí),是的在函數(shù)調(diào)用更加直觀明了?
解包參數(shù)
我們可以在函數(shù)調(diào)用時(shí),直接利用*和**進(jìn)行參數(shù)傳遞,然后讓函數(shù)自動(dòng)解包,也就類(lèi)似之前的序列解包,使用調(diào)用時(shí)更加的直觀。
def
f
(
a
,
b
,
c
,
d
)
:
print
(
a
,
b
,
c
,
d
)
f
(
1
,
*
(
2
,
3
)
,
**
{
'd'
:
4
}
)
示例結(jié)果:
1 2 3 4
更多文章、技術(shù)交流、商務(wù)合作、聯(lián)系博主
微信掃碼或搜索:z360901061

微信掃一掃加我為好友
QQ號(hào)聯(lián)系: 360901061
您的支持是博主寫(xiě)作最大的動(dòng)力,如果您喜歡我的文章,感覺(jué)我的文章對(duì)您有幫助,請(qǐng)用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點(diǎn)擊下面給點(diǎn)支持吧,站長(zhǎng)非常感激您!手機(jī)微信長(zhǎng)按不能支付解決辦法:請(qǐng)將微信支付二維碼保存到相冊(cè),切換到微信,然后點(diǎn)擊微信右上角掃一掃功能,選擇支付二維碼完成支付。
【本文對(duì)您有幫助就好】元
