python中的*args 和**kwargs
Posted Apollo
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python中的*args 和**kwargs相关的知识,希望对你有一定的参考价值。
*args是可变长参数,在函数内部以tuple形式存储;
def fun_var_args(farg, *args): print "arg:", farg print(type(args))
>>> fun_var_args(1, ‘two‘, 3)
arg: 1
<type ‘tuple‘>
def fun_var_args(farg, *args): print "arg:", farg for value in args: print "another arg:", value
>>>fun_var_args(1, "two",3)
arg: 1
another arg: two
another arg: 3
对于参数**kwargs,输入时要指定key和value
def fun_var_kwargs(farg, **kwargs): print "arg:", farg for key in kwargs: print "another keyword arg: %s: %s" % (key, kwargs[key])
>>>fun_var_kwargs(farg=1, myarg2=‘two‘, myarg3=3)
arg: 1
another keyword arg: myarg2: two
another keyword arg: myarg3: 3
参数kwargs在函数内部存储为dict:
def fun_var_kwargs(farg, **kwargs): print "arg:", farg print(type(kwargs))
>>>fun_var_kwargs(farg=1, myarg2=‘two‘, myarg3=3)
arg: 1
<type ‘dict‘>
以上是关于python中的*args 和**kwargs的主要内容,如果未能解决你的问题,请参考以下文章