python函数可变参数语言_python 函数参数个数可变

如果用过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}

函数接受参数的顺序, 先接受固定参数,然后是可选参数,然后接受任意参数,最后是带名字的任意参数.

发表于 2008-11-11 14:28 明明 阅读(1425) 评论(0)  编辑 收藏 引用

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值