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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值