python 可变参数函数定义* args和**kwargs的用法

python函数可变参数 (Variable Argument) 的方法:使用*args和**kwargs语法。其中,*args是可变的positional arguments列表,**kwargs是可变的keyword arguments列表。并且,*args必须位于**kwargs之前,因为positional arguments必须位于keyword arguments之前

下面一个例子使用*args,同时包含一个必须的参数:

[python] view plain copy
 
  1. def test_args(first, *args):  
  2.    print 'Required argument: ', first  
  3.    for v in args:  
  4.       print 'Optional argument: ', v  
  5.   
  6. test_args(1, 2, 3, 4)  
  7. # result:  
  8. # Required argument: 1  
  9. # Optional argument:  2  
  10. # Optional argument:  3  
  11. # Optional argument:  4  

下面一个例子使用*kwargs, 同时包含一个必须的参数和*args列表:

[python] view plain copy
 
  1. def test_kwargs(first, *args, **kwargs):  
  2.    print 'Required argument: ', first  
  3.    for v in args:  
  4.       print 'Optional argument (*args): ', v  
  5.    for k, v in kwargs.items():  
  6.       print 'Optional argument %s (*kwargs): %s' % (k, v)  
  7.   
  8. test_kwargs(1, 2, 3, 4, k1=5, k2=6)  
  9. # results:  
  10. # Required argument:  1  
  11. # Optional argument (*args):  2  
  12. # Optional argument (*args):  3  
  13. # Optional argument (*args):  4  
  14. # Optional argument k2 (*kwargs): 6  
  15. # Optional argument k1 (*kwargs): 5  

*args和**kwargs语法不仅可以在函数定义中使用,同样可以在函数调用的时候使用。不同的是,如果说在函数定义的位置使用*args和**kwargs是一个将参数pack的过程,那么在函数调用的时候就是一个将参数unpack的过程了。下面使用一个例子来加深理解:

[python] view plain copy
 
  1. # Use *args  
  2. args = [1, 2, 3, 4, 5]  
  3. test_args(*args)  
  4. # results:  
  5. # First argument:  1  
  6. # Second argument:  2  
  7. # Third argument:  3  
  8. # Fourth argument:  4  
  9. # Fifth argument:  5  
  10.   
  11. # Use **kwargs  
  12. kwargs = {  
  13.     'first': 1,  
  14.     'second': 2,  
  15.     'third': 3,  
  16.     'fourth': 4,  
  17.     'fifth': 5  
  18. }  
  19.   
  20. test_args(**kwargs)  
  21. # results:  
  22. # First argument:  1  
  23. # Second argument:  2  
  24. # Third argument:  3  
  25. # Fourth argument:  4  
  26. # Fifth argument:  5  
原文地址:https://www.cnblogs.com/AmilyWilly/p/6861792.html