Python *args **kw
当函数的参数不确定时,可以使用*args 和**kwargs,*args 没有key值,**kwargs有key值。
- *args
def fun_var_args(farg, *args): print "arg:", farg for value in args: # *args可以当作可容纳多个变量组成的list print "another arg:", value fun_var_args(1,'aa',123,'bb')
#输出 arg: 1 another arg: aa another arg: 123 another arg: bb
- **kw
def fun_var_kw(farg, **kw): print "arg:", farg for key in kw: #**kwargs可以当作容纳多个key和value的dictionary print "another keyword arg: %s: %s" % (key, kw[key]) fun_var_kw(1,a='aa',c=123,b='bb')
- 两者同时使用
def fun_var_arg_and_kw(farg, *args, **kw): print "arg:", farg for value in args: print "another arg:", value for key in kw: print "another keyword arg: %s: %s" % (key, kw[key]) fun_var_arg_and_kw(1,'qq','ww','ee',a='aa',c=123,b='bb')