溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

函數(shù)參數(shù)調(diào)用和非固定參數(shù)的示例分析

發(fā)布時(shí)間:2021-10-21 13:55:32 來(lái)源:億速云 閱讀:144 作者:小新 欄目:編程語(yǔ)言

這篇文章給大家分享的是有關(guān)函數(shù)參數(shù)調(diào)用和非固定參數(shù)的示例分析的內(nèi)容。小編覺(jué)得挺實(shí)用的,因此分享給大家做個(gè)參考,一起跟隨小編過(guò)來(lái)看看吧。

def test(x,y,z): #這添加形參
print(x)
print(y)
print(z)
test(1,2,3)  # 這里添加實(shí)參

1、形參和實(shí)參

2、位置參數(shù)和關(guān)鍵字

#test(1,2)#位置參數(shù)調(diào)用:實(shí)參與形參一一對(duì)應(yīng),不能多,不能少
#test(y=1,x=2)#關(guān)鍵字 :與形參順序無(wú)關(guān)
#test(y=1,x=2,1)# 關(guān)鍵字參數(shù)不能放在位置參數(shù)前面
#test(1,z=2,y=5)

3、默認(rèn)參數(shù):調(diào)用函數(shù)的時(shí)候,默認(rèn)函數(shù)可有可無(wú)。

用途:1.默認(rèn)安裝值 2.固定默認(rèn)值

def test(x,y=2):
print(x)
print(y)
test(1,y=3)

參數(shù)組:參數(shù)組要放在最后面如test3(name,x=2,*args)

#def test(*gg): #可接受任意數(shù)量實(shí)參,變成元組的形式
print(gg)

test(1,2,3,4,5,5,5,5,5,7,9)
test(*[1,2,3,4,5]) #  gg=tuple([1,2,3,4,5])

*args:接受n者位置參數(shù),轉(zhuǎn)換成元組

def test(x,args): # 號(hào)代表功能
print(x)
print(args)

#test(1,2,3,4,5,6,7)
#test([1,2,3,4,5,6,7]) #args=*[1,2,3,4,5,6,7]

接受n個(gè)關(guān)鍵字參數(shù),轉(zhuǎn)成字典的形式

def test1(**kwargs):!
print(kwargs)
print(kwargs["name"])
print(kwargs["age"])

test1(name="alex",age=8) #把n個(gè)關(guān)鍵字參數(shù),轉(zhuǎn)換成字典
test1(**{"name":"alex","age":"8"})

位置參數(shù)和關(guān)鍵字參數(shù)

#def test3(name,**kwargs):
print(name)
print(kwargs)

test3("alex",age=18,sex="m")

默認(rèn)參數(shù),位置參數(shù),關(guān)鍵字參數(shù)

def test3(name,x=2,**kwargs):
print(name)
print(x)
print(kwargs)

test3("alex",age=18,sex="m",x=4)

def test3(name,x=2,*args,**kwargs):
print(name)
print(x)
print(args)
print(kwargs)

test3("alex",age=18,sex="m",x=4)

總結(jié):位置參數(shù)只會(huì)傳給形參和*args,關(guān)鍵字參數(shù)傳給*kwargs!
args會(huì)把n個(gè)位置參數(shù)轉(zhuǎn)換成元祖的形式!
**kwargs會(huì)把n個(gè)關(guān)鍵字參數(shù)轉(zhuǎn)換成字典形式!m=‘a(chǎn)lex’ (m是key,‘a(chǎn)lex’是values)

感謝各位的閱讀!關(guān)于“函數(shù)參數(shù)調(diào)用和非固定參數(shù)的示例分析”這篇文章就分享到這里了,希望以上內(nèi)容可以對(duì)大家有一定的幫助,讓大家可以學(xué)到更多知識(shí),如果覺(jué)得文章不錯(cuò),可以把它分享出去讓更多的人看到吧!

向AI問(wèn)一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI