参数个数确定
>>> def func(x,y):
最常见,列出有限个的参数,彼此用逗号隔开。调用函数的时候,按照顺序依次对参数进行复制,参数名字不重要,重要的是位置,位置一致并且一一对应,正所谓,一个萝卜一个坑。
参数个数不确定
def foo(*args)
>>> def func(x,*arg):
... print x
... result = x
... print arg
... for i in arg:
... result += i
... return result
...
>>> print func(1,2,3,4,5,6,7,8,9)
1
(2, 3, 4, 5, 6, 7, 8, 9)
45
可以看出,参数个数不确定的时候,其他参数全部通过*arg,以元组的形式由arg收集起来。对照上面例子不难发现:
- 值1传给了参数x
- 值2,3,4,5,6,7,8,9被塞入一个tuple里面,传给arg
>>> def foo(*args):
... print args
...
>>> foo(1,2,3)
(1, 2, 3)
>>> foo("iphone","xiaomi","oppo")
('iphone', 'xiaomi', 'oppo')
>>> foo("qiwsir",307,["qiwsir",2],{"name":"qiwsir","lang":"python"})
('qiwsir', 307, ['qiwsir', 2], {'lang': 'python', 'name': 'qiwsir'})
如果参数只有一个,也同样,塞进tuple,逗号保留:
>>> def func(*arg):
... return arg
...
>>> func(1)
(1,)
>>>
def foo(**args)
这种方式跟上面的区别在于,必须接收类似 arg=val 形式的。
>>> def func(**args):
... print args
...
>>> foo(1,2) #报错
>>> func(a=1,b=2,c=3) # 参数以键值对的形式传递
{'a': 1, 'c': 3, 'b': 2}
>>>
综合以上几种情况:
>>> def func(x,y=2,*targs,**dargs):
... print "x==",x
... print "y==",y
... print "targs==",targs
... print "dargs==",dargs
...
>>> func("1x")
x== 1x
y== 2
targs== ()
dargs== {}
>>> func("1x","2y")
x== 1x
y== 2y
targs== ()
dargs== {}
>>> func("1x","2y","3t1","3t2")
x== 1x
y== 2y
targs== ('3t1', '3t2')
dargs== {}
>>> func("1x","2y","3t1","3t2",d1="4d1",d2="4d2")
x== 1x
y== 2y
targs== ('3t1', '3t2')
dargs== {'d2': '4d2', 'd1': '4d1'}
>>>
网友评论