函数定义时有时会使用*args
和**kwargs
,学习这两个参数的作用
def func(arg, *args, **kwargs):
pass
函数定义时,arg
*args
**kwargs
三者顺序不能颠倒,否则会报错。
*args
将参数打包成元组后传给func
,**kwargs
将键——值类型的参数打包成字典后传给func
。
def func(arg, *args, **kwargs):
print('This is the arg: ', arg)
print('This is the args: ', args)
print('This is the kwargs: ', kwargs)
def main():
func(1, 2, [4, 5, 6], (7, 8), a=9, b=10)
实验结果:
This is the arg: 1
This is the args: (2, [4, 5, 6], (7, 8))
This is the kwargs: {‘a’: 9, ‘b’: 10}