*args和**kwargs
*args和**kwargs主要用于函数定义,可以将不定量的参数传给一个函数
(ps:不是必须写成*args和**kwargs,只有变量前面的*[星号]才是必须的,也可以写成*var和**vars,*args和**kwargs只是一个通俗的定义)
以下来介绍这俩
1.*args的用法
*args是用来发送一个非键值对的可变数量的参数列表给一个函数。举例如下
#/usr/bin/python def test_args(argv1,*args): print "first arg is " + argv1 for arg in args: print "another arg is " + arg test_args("first","python","nodejs")
执行结果如下:
first arg is first another arg is python another arg is nodejs
2.**kwargs的用法
**kwargs是用来将不定长度的键值对作为参数传给一个函数。举例如下:
#!/usr/bin/python def test_kwargs(**kwargs): for key ,value in kwargs.items(): print key + " is " + value test_kwargs(name="zhaolibin",age="18")
执行结果如下:
age is 18 name is zhaolibin
3.假如你要同时传入上述两种参数,则需要用以下顺序
some_func(fargs, *args, **kwargs) 举例如下:
#!/usr/bin/python def test_kwargs(farg,*argvs,**kwargs): print "farg is " + farg for arg in argvs: print "another arg is " + arg for key ,value in kwargs.items(): print key + " is " + value test_kwargs("first","second","third",name="zhaolibin",age="18")
执行结果如下:
farg is first another arg is second another arg is third age is 18 name is zhaolibin