*args和 **kwargs一般用在函数定义的时候。二者允许函数接受可变参数,其中,*args是可变的positional arguments列表,**kwargs 是可变的keyword arguments列表。并且,*args必须位于 **kwargs之前,因为positional arguments必须位于keyword arguments之前。
*args
def test_var_args(f_arg, *argv):
print("first normal arg:", f_arg)
for arg in argv:
print("another arg through *argv:", arg)
test_var_args('yasoob', 'python', 'eggs', 'test')
结果:
first normal arg: yasoob
another arg through *argv: python
another arg through *argv: eggs
another arg through *argv: test
**kwargs
def greet_me(**kwargs):
for key, value in kwargs.items():
print("{0} = {1}".format(key, value))
greet_me(name="yasoob")
结果:
name = yasoob