*args 和 **kwargs的概念
*args和**kwargs是两个魔法变量。*args是用来发送一个非键值对的可变数量的参数列表给一个函数。**kwargs允许你将不定长度的键值对, 作为参数传递给一个函数。*args和**kwargs只是一个通俗的命名约定。并不是必须写成*args和**kwargs,只有变量前面的*(星号)才是必须的。
使用*args传递及处理任意多个非键值对参数
python
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')这会产生如下输出:
bash
first normal arg: yasoob
another arg through *argv: python
another arg through *argv: eggs
another arg through *argv: test案例:使用**kwargs传递及处理任意多个键值对参数
python
def greet_me(**kwargs):
for key, value in kwargs.items():
print("{key} == {value}")
>>> greet_me(name="yasoob")
name == yasoob现在你可以看出我们怎样在一个函数里, 处理了一个键值对参数了。