[转]Python的函数参数形式

aries 发表于 2012-10-25 1369 次浏览

Python函数参数可以用星号+形参名形式(arg或**arg)方式。其中arg方式必须在传统参数后边出现,而**arg则必须在*arg后出现。

例如:
def test(x, y=5, *a, **b):
    print x, y, a, b

函数调用结果:

test(1) ===> 1 5 () {}
test(1,2) ===> 1 2 () {}
test(1,2,3)  ===> 1 2 (3,) {}
test(1,2,3,4) ===> 1 2 (3,4)
test(x=1)   ===> 1 5 () {}
test(x=1,y=1)  ===> 1 1 () {}
test(x=1,y=1,a=1)   ===> 1 1 () {'a':1}
test(x=1,y=1,a=1,b=1)   ===> 1 1 () {'a':1,'b':1}
test(1,y=1) ===> 1 1 () {}
test(1,2,y=1) ===> 出错,说y给赋了多个值
test(1,2,3,4,a=1) ===> 1 2 (3,4) {'a':1}
test(1,2,3,4,k=1,t=2,o=3) ===> 1 2 (3,4) {'k':1,'t':2,'o':3}

0条评论

如需评论,请填写表单。
换一个

记住我的信息