*args and **kwargs
并不是必须写成这样,只有变量前面的(*)才是必须的
主要用于函数定义,可以将不定数量的参数传递给一个函数
# 不定的意思是:预先并不知道,函数使用者会传递多少个参数
# *arg 是用来发送一个非键值对的可变数量的参数列表给一个函数
def test_var_args(f_arg, *args):
print("first normal arg:", f_arg)
for arg in args:
print("another arg through *args:", arg)
test_var_args('google','python','pytorch','tensorflow')
first normal arg: google
another arg through *args: python
another arg through *args: pytorch
another arg through *args: tensorflow
# **kwargs 允许将不定长度的键值对,作为参数传递给一个函数。比如处理带名字的参数
def greet_me(**kwargs):
for key, value in kwargs.items():
print("{0} == {1}".format(key, value))
greet_me(name="python")
name == python
# 使用*args 和 **kwargs来调用函数
def test_args_kwargs(arg1, arg2, arg3):
print("arg1:", arg1)
print("arg2:", arg2)
print("arg3:", arg3)
args = ("python", 3, 5)
test_args_kwargs(*args)
arg1: python
arg2: 3
arg3: 5
kwargs = {"arg1": 3, "arg2": "python", "arg3": 5}
test_args_kwargs(**kwargs)
arg1: 3
arg2: python
arg3: 5
注意:标准参数与* args 和 ** kwargs 在使用时的顺序是:
some_func(fargs, * args, ** kwargs)
什么时候使用?
最常见的就是在写函数装饰器的时候