Python中*args和**kwargs的区别
*args和**kwargs的使用方法
- *args 用来将参数打包成tuple给函数体调用
- **kwargs 打包关键字参数成dict给函数体调用
def test_args(first, *args, **kwargs):
print('Required argument: ', first)
print('Optional argument: ', args)
print('Optional argument: ', kwargs)
test_args(1, 2, 3, 4)
test_args(1, k1=2, k2=3, k3=4)
test_args(1, 2, k2=3, k3=4)
运行结果:
Required argument: 1
Optional argument: (2, 3, 4)
Optional argument: {}
===============================================
Required argument: 1
Optional argument: ()
Optional argument: {'k3': 4, 'k1': 2, 'k2': 3}
===============================================
Required argument: 1
Optional argument: (2,)
Optional argument: {'k3': 4, 'k2': 3}