Python的args和kwargs理解

众所周知,python的args是用来接收不定长的参数,而kwargs是用来接收不定长的关键字参数。

下面通过实例来看看如何真正的理解这两个的用法。

def test2(a, b, *args, **kwargs):
    print("------test2---------")
    print(a)
    print(b)
    print(args)
    print(kwargs)

def test1(a, b, *args, **kwargs):
    print("-------test1---------")
    print(a)
    print(b)
    print(args)
    print(kwargs)
    print("The output of a, b, args, kwargs")
    test2(a, b, args, kwargs)
    print("The output of a, b, *args, kwargs")
    test2(a, b, *args, kwargs)
    print("The output of a, b, *args, **kwargs")
    test2(a, b, *args, **kwargs)


test1(11,22,33,44,55,66, name="zhangsan", age=18)

The output of the test code like following:

-------test1---------
11
22
(33, 44, 55, 66)
{‘name’: ‘zhangsan’, ‘age’: 18}

The output of a, b, args, kwargs
------test2---------
11
22
((33, 44, 55, 66), {'name': 'zhangsan', 'age': 18})
{}

从这个结果来看,(33, 44, 55, 66), {‘name’: ‘zhangsan’, ‘age’: 18}被作为一个整体传给了test2函数的args对象;然后kwargs没有实参。

 The output of a, b, *args, kwargs
    ------test2---------
    11
    22
    (33, 44, 55, 66, {'name': 'zhangsan', 'age': 18})
    {}

从这个结果来看,(33, 44, 55, 66, {‘name’: ‘zhangsan’, ‘age’: 18})被作为一个整体传给了test2函数的args对象;然后kwargs没有实参。

The output of a, b, *args, **kwargs
    ------test2---------
    11
    22
    (33, 44, 55, 66)
    {'name': 'zhangsan', 'age': 18}

从这个结果来看,(33, 44, 55, 66)被作为一个整体传给了test2函数的args对象; {‘name’: ‘zhangsan’, ‘age’: 18}传给了kwargs参数,这个才是我们期待的结果。

总结起来,可以这么理解,*args可以理解为对实参的一个拆包,**args也是对实参的拆包。不带星花就不拆包,会被当做一个整体

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值