任意参数个数的函数是一种很方便的设计。
通过在函数定义的时候,指明*args,这个就表示函数接收任意个数参数。有*args,同时还可以有别的所谓的位置参数(positional argument),键值参数(keyword argument),可以混用。
下面是我自己写的一个学习函数,注意*args传递进来的是一个tuple:
>>>
>>> def test1(*args):
... print(args)
...
>>>
>>> test1(1,'b',6,'y',1.56)
(1, 'b', 6, 'y', 1.56)
>>>
>>> test1('kkkk')
('kkkk',)
>>>
>>>
>>> test1('kkkk',77)
('kkkk', 77)
>>>
*args的写法,重点在*,而不是args,你也可以协成*arggss,或者*kkk。反正记住,都是tuple。
函数设计时,一个*表示tuple,两个**表示dict,如下代码:
>>>
>>> def test2(**kwargs):
... print(kwargs)
...
>>>
>>> test2(k1=1,k2=2,k3=3)
{'k1': 1, 'k2': 2, 'k3': 3}
>>>
>>> test2(k4=4)
{'k4': 4}
>>>
2018-09-27:
Python中有一种叫做Unpacking Argument的操作,也可以用来理解其不定参数函数接口的设计思路,我们通过官方给出的两个代码段来学习吧:
>>> list(range(3, 6)) # normal call with separate arguments
[3, 4, 5]
>>> args = [3, 6] # args = (3, 6) is also OK
>>> list(range(*args)) # call with arguments unpacked from a list
[3, 4, 5]
#######
>>> def parrot(voltage, state='a stiff', action='voom'):
... print("-- This parrot wouldn't", action, end=' ')
... print("if you put", voltage, "volts through it.", end=' ')
... print("E's", state, "!")
...
>>> d = {"voltage": "four million", "state": "bleedin' demised", "action": "VOOM"}
>>> parrot(**d)
-- This parrot wouldn't VOOM if you put four million volts through it. E's bleedin' demised !
*:提取List或Tuple;
**:提取Dict。