参考:http://kodango.com/variable-arguments-in-python
参考:https://www.cnblogs.com/yunguoxiaoqiao/p/7626992.html
python支持可变参数,以默认参数为例:
def test_defargs(one, two = 2): print ('Required argument: ', one) print ('Optional argument: ', two) test_defargs(1) #返回 #Required argument: 1 #Optional argument: 2
其中,*args和**kwargs则是用于实现可变参数的方法。*args是可变的positional arguments列表,**kwargs是可变的keyword arguments列表。并且*args必须位于**kwargs前,这是因为positional arguments必须位于keyword arguments前。
*args的基本用法如下,包含一个必须的参数:
def function(*args): print(args, type(args)) function(1) #返回tuple格式数据
def function(x, y, *args): print(x, y, args) function(1, 2, 3, 4, 5) #返回 1,2,(3,4,5)
def test_args(first, *args): print ('Required argument: ', first) for v in args: print ('Optional argument: ', v) test_args(1, 2, 3, 4) #返回 #Required argument: 1 #Optional argument: 2 #Optional argument: 3 #Optional argument: 4
**kwargs的基本用法如下,包含一个必须的参数和*args列表
def function(**kwargs): print( kwargs, type(kwargs)) function(a=2) #返回{'a': 2} <class 'dict'>
def function(**kwargs): print(kwargs) function(a=1, b=2, c=3) #返回 {'a': 1, 'b': 2, 'c': 3}
def function(arg,*args,**kwargs): print(arg,args,kwargs) function(6,7,8,9,a=1, b=2, c=3) #返回 6 (7, 8, 9) {'a': 1, 'b': 2, 'c': 3}
def test_kwargs(first, *args, **kwargs): print ('Required argument: ', first) for v in args: print ('Optional argument (*args): ', v) for k, v in kwargs.items(): print ('Optional argument %s (*kwargs): %s' % (k, v)) test_kwargs(1, 2, 3, 4, k1=5, k2=6) #返回 #Required argument: 1 #Optional argument (*args): 2 #Optional argument (*args): 3 #Optional argument (*args): 4 #Optional argument k1 (*kwargs): 5 #Optional argument k2 (*kwargs): 6