如果用过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} 函数接受参数的顺序, 先接受固定参数,然后是可选参数,然后接受任意参数,最后是带名字的任意参数.