Python学习之路(45)—— *args和**kwargs
*args和**kwargs
主要用于函数定义,可以将不定数量的参数传递给一个函数。
前者用来发送一个非键值对的可变数量参数列表给函数,后者用来发送键值对的可变数量参数列表给函数。
先看*args的例子:
def test_var_args(f_arg, *args):
print("first normal arg:", f_arg)
print("another arg *args:", args)
test_var_args('nicolas', 'python', 'eggs', 'test', 'world')
##########执行结果##########
first normal arg: nicolas
another arg *args: ('python', 'eggs', 'test', 'world')
如果还想再*args后再加一个参数的话,传递给函数的参数需要使用关键字参数,不然会报错,比如:
#不使用关键词参数:
def test_var_args(f_arg, *args, l_arg):
print("first normal arg:", f_arg)
print("another arg *args:", args)
print("last normal arg:", l_arg)
test_var_args('nicolas', 'python', 'eggs', 'test', 'world')
##########执行结果##########
Traceback (most recent call last):
File "D:/Project/Python/Pro_py3/test.py", line 6, in <module>
test_var_args('nicolas', 'python', 'eggs', 'test', 'world')
TypeError: test_var_args() missing 1 required keyword-only argument: 'l_arg'
#使用了关键字参数
def test_var_args(f_arg, *args, l_arg):
print("first normal arg:", f_arg)
print("another arg *args:", args)
print("last normal arg:", l_arg)
test_var_args('nicolas', 'python', 'eggs', 'test', l_arg='world')
##########执行结果##########
first normal arg: nicolas
another arg *args: ('python', 'eggs', 'test')
last normal arg: world
再看**kwargs的例子:
def test_var_args(f_arg, **kwargs):
print("first normal arg:", f_arg)
print("another arg *kwargs:", kwargs)
test_var_args('nicolas', keyword1 = 'hello', keyword2 = 'python')
##########执行结果##########
first normal arg: nicolas
another arg *kwargs: {'keyword2': 'python', 'keyword1': 'hello'}
注意,使用了**kwargs之后就不能用参数了,否则会报错:
def test_var_args(f_arg, **kwargs, hi = 0):
print("first normal arg:", f_arg)
print("another arg *kwargs:", kwargs)
test_var_args('nicolas', keyword1 = 'hello', keyword2 = 'python')
##########执行结果##########
File "D:/Project/Python/Pro_py3/test.py", line 1
def test_var_args(f_arg, **kwargs, hi = 0):
^
SyntaxError: invalid syntax
因此,标准参数与*args、**kwargs的顺序是:
function(arg, *args, **kwargs)
浙公网安备 33010602011771号