新聞中心
函數(shù)的參數(shù)使用除了常規(guī)的位置參數(shù)和關(guān)鍵字參數(shù)外,還支持可變個數(shù)的函數(shù)參數(shù),這種支持可變個數(shù)的參數(shù)方法稱為參數(shù)收集,對應(yīng)的參數(shù)稱為收集參數(shù)。

一、參數(shù)收集的定義
Python的函數(shù)支持可變不定數(shù)量的參數(shù)模式,這種將不定數(shù)量實參在調(diào)用時傳遞給函數(shù),函數(shù)將其識別并保存到指定形參的過程稱為參數(shù)收集:
1、帶一個星號的參數(shù)收集模式
這種模式是在函數(shù)定義時在某個形參前面加一個星號,調(diào)用時按位置匹配不帶星號的形參和實參,多余的實參都將作為一個元組的元素保存到星號對應(yīng)的形參中,該星號后的形參就稱為收集參數(shù)。
這種模式的參數(shù)收集過程與前面介紹的序列解包類似,只是序列解包是將序列中多出的部分存放到星號后面的列表變量,而函數(shù)收集是將多出的參數(shù)存放到收集參數(shù)對應(yīng)的元組變量。這種模式的參數(shù)收集與序列解包類似,收集參數(shù)最好是最后一個形參,但可以出現(xiàn)在函數(shù)參數(shù)的任何位置,只是此時該參數(shù)后面的參數(shù)在調(diào)用時必須用關(guān)鍵字參數(shù)模式傳值,否則這些實參值都將作為收集參數(shù)的一部分。
舉例:我們來實現(xiàn)一個計算函數(shù),其終極目標(biāo)是輸入一串不限數(shù)量的數(shù)字,然后調(diào)用對應(yīng)的運算符進行連續(xù)運算(如連加、連減、連乘等)。為了突出重點,我們在最初的例子只是定義這個函數(shù)并輸出參數(shù)值,以來驗證上面相關(guān)描述對于形參和實參的取值方法。后面章節(jié)再來完整實現(xiàn)該函數(shù)。
函數(shù)定義:
\>>> def cal(number1,number2=None,*numbers,calmethod='$'):
print('number1=',number1,',number2=',number2,',numbers=',numbers,', calmethod=',calmethod)函數(shù)調(diào)用執(zhí)行:
\>>> cal(1,'+')
number1= 1 ,number2= + ,numbers= () , calmethod= $
\>>> cal(1,2,'+')
number1= 1 ,number2= 2 ,numbers= ('+',) , calmethod= $
\>>> cal(1,2,3,'+')
number1= 1 ,number2= 2 ,numbers= (3, '+') , calmethod= $
\>>> cal(1,2,3,4,'+')
number1= 1 ,number2= 2 ,numbers= (3, 4, '+') , calmethod= $
\>>> cal(1,calmethod='+')
number1= 1 ,number2= None ,numbers= () , calmethod= +
\>>> cal(1,2,calmethod='+')
number1= 1 ,number2= 2 ,numbers= () , calmethod= +
\>>> cal(1,2,3,calmethod='+')
number1= 1 ,number2= 2 ,numbers= (3,) , calmethod= +
\>>> cal(1,2,3,4,calmethod='+')
number1= 1 ,number2= 2 ,numbers= (3, 4) , calmethod= +
\>>>執(zhí)行截圖如下:
2、帶兩個星號的參數(shù)收集模式
第一種模式的收集參數(shù)不能收集關(guān)鍵字參數(shù)傳遞的實參,要收集關(guān)鍵字參數(shù)傳遞的實參,需要在收集參數(shù)前使用兩個星號,此時收集參數(shù)對應(yīng)的是一個字典而不是元組。
此種模式的收集參數(shù)必須放在函數(shù)的最后一個,這是因為關(guān)鍵字參數(shù)的函數(shù)參數(shù)之后不允許出現(xiàn)非關(guān)鍵字參數(shù)。此種情況的關(guān)鍵字參數(shù)的參數(shù)名,并不是上節(jié)內(nèi)容介紹的函數(shù)定義中的關(guān)鍵字參數(shù)名,而是在實參調(diào)用時采用關(guān)鍵字參數(shù)形式傳遞的不定數(shù)量的參數(shù)。 兩種模式的收集參數(shù)可以混用。
\>>> def cal(calmethod='+',*topnopers,**lastnopers):
print('運算符=',calmethod,',前幾個運算參數(shù)為=',topnopers,',最后幾個運算參數(shù)=',lastnopers)
\>>> cal('+',1,2,3,4,n5=5,n6=6,n7=7)運算符= + ,前幾個運算參數(shù)為= (1, 2, 3, 4) ,最后幾個運算參數(shù)= {'n5': 5, 'n6': 6, 'n7': 7}
分享文章:創(chuàng)新互聯(lián)Python教程:詳解Python函數(shù)中參數(shù)帶星號是什么意思
網(wǎng)站網(wǎng)址:http://m.fisionsoft.com.cn/article/cdshcho.html


咨詢
建站咨詢
