1.Python中也有像C++一樣的默認缺省函數(shù)
def foo(text,num=0):
print text,num
foo("asd") #asd 0
foo("def",100) #def 100
定義有默認參數(shù)的函數(shù)時,這些默認值參數(shù) 位置必須都在非默認值參數(shù)后面。
調用時提供默認值參數(shù)值時,使用提供的值,否則使用默認值。
2.Python可以根據(jù)參數(shù)名傳參數(shù)
def foo(ip,port):
print "%s:%d" % (ip,port)
foo("192.168.1.0",3306) #192.168.1.0:3306
foo(port=8080,ip="127.0.0.1") #127.0.0.1:8080
第4行,沒有指定參數(shù)名,按照順序傳參數(shù)。
第5行,指定參數(shù)名,可以按照參數(shù)名稱傳參數(shù)。
3.可變長度參數(shù)
#coding:utf-8 #設置python文件的編碼為utf-8,這樣就可以寫入中文注釋
def foo(arg1,*tupleArg,**dictArg):
print "arg1=",arg1 #formal_args
print "tupleArg=",tupleArg #()
print "dictArg=",dictArg #[]
foo("formal_args")
上面函數(shù)中的參數(shù),tupleArg前面“*”表示這個參數(shù)是一個元組參數(shù),從程序的輸出可以看出,默認值為();dicrtArg前面有“**”表示這個字典參數(shù)(鍵值對參數(shù))??梢园裻upleArg、dictArg看成兩個默認參數(shù)。多余的非關鍵字參數(shù),函數(shù)調用時被放在元組參數(shù)tupleArg中;多余的關鍵字參數(shù),函數(shù)調用時被放字典參數(shù)dictArg中。
下面是可變長參數(shù)的一些用法:
#coding:utf-8 #設置python文件的編碼為utf-8,這樣就可以寫入中文注釋
def foo(arg1,arg2="OK",*tupleArg,**dictArg):
print "arg1=",arg1
print "arg2=",arg2
for i,element in enumerate(tupleArg):
print "tupleArg %d-->%s" % (i,str(element))
for key in dictArg:
print "dictArg %s-->%s" %(key,dictArg[key])
myList=["my1","my2"]
myDict={"name":"Tom","age":22}
foo("formal_args",arg2="argSecond",a=1)
print "*"*40
foo(123,myList,myDict)
print "*"*40
foo(123,rt=123,*myList,**myDict)
輸出為:
從上面的程序可以看出:
(1)如代碼第16行。
參數(shù)中如果使用“*”元組參數(shù)或者“**”字典參數(shù),這兩種參數(shù)應該放在參數(shù)列表最后。并且“*”元組參數(shù)位于“**”字典參數(shù)之前。
關鍵字參數(shù)rt=123,因為函數(shù)foo(arg1,arg2="OK",*tupleArg,**dictArg)中沒有rt參數(shù),所以最后也歸到字典參數(shù)中。
(2)如代碼第14行。
元組對象前面如果不帶“*”、字典對象如果前面不帶“**”,則作為普通的對象傳遞參數(shù)。
多余的普通參數(shù),在foo(123,myList,myDict)中,123賦給參數(shù)arg1,myList賦給參數(shù)arg2,多余的參數(shù)myDict默認為元組賦給myList。