当函数遇到不确定数量参数肿么破?*args和**kwargs前来报道!
*args **kwargs
当函数的参数不确定时,可以使用*args 和**kwargs,*args 没有key值,**kwargs有key值。
>>>def fun_var_args(farg, *args):
>>> print "arg:", farg
>>> for value in args:
>>> print "another arg:", value
>>>fun_var_args(1, "two", 3) # *args可以当作可容纳多个变量组成的list
result:
arg: 1
another arg: two
another arg: 3
**kwargs:
>>>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) # myarg2和myarg3被视为key, 感觉**kwargs可以当作容纳多个key和value的dictionary
result:
arg: 1
another keyword arg: myarg2: two
another keyword arg: myarg3: 3
时间: 2024-11-07 15:05:32