如果用過C語言中的printf(),那么就會對參數個數可變的意義比較了解. 盡管可選參數的機制令函數的參數個數是可變的,但是還是有限制的,參數個數有最大限制,而且還要指明哪些是可選參數,而下面這個機制,可以接受任意多個參數. >>> def printf(format,*arg): ... print format%arg ... >>> printf ("%d is greater than %d",1,2) 1 is greater than 2 其中*arg必須是最后一個參數, *表示接受任意多個參數,除了前面的參數后,多余的參數都作為一個tuple傳遞給函數printf,可以通過arg來訪問. 還有一種方式來實現任意個數參數, 就是參數按照dictionary的方式傳遞給函數, 函數同樣可以接受任意多個參數. >>> def printf(format,**keyword): ... for k in keyword.keys(): ... print "keyword[%s] is %s"%(k,keyword[k]) ... >>> printf("ok",One=1,Two=2,Three=3) keyword[Three] is 3 keyword[Two] is 2 keyword[One] is 1 同上一種機制類似, 只不過**keyword是用**表示接受任意個數的有名字的參數傳遞,但是調用函數時,要指明參數的名字,one=1,two=2... 在函數中, 可以用dictionary的方式來操作keyword,其中keys是['one','two','three'],values是[1,2,3]. 還可以將兩種機制和在一起, 這時, *arg,要放在**keyword前面. >>> printf("%d is greater than %d",2,1,Apple="red",One="1") 2 is greater than 1 keyword[Apple]=red keyword[One]=1 >>> def testfun(fixed,optional=1,*arg,**keywords): ... print "fixed parameters is ",fixed ... print "optional parameter is ",optional ... print "Arbitrary parameter is ", arg ... print "keywords parameter is ",keywords ... >>> testfun(1,2,"a","b","c",one=1,two=2,three=3) fixed parameters is 1 optional parameter is 2 Arbitrary parameter is (’a’, ’b’, ’c’) keywords parameter is {’three’: 3, ’two’: 2, ’one’: 1} 函數接受參數的順序, 先接受固定參數,然后是可選參數,然后接受任意參數,最后是帶名字的任意參數.