python *args 和 ** kwargs

可变长度的参数

*args的使用方法

      *args 用来将参数打包成tuple给函数体调用

 

可见,1这个参数,被打包成了一个元组

1

2

3

4

5

6

def func(*args):

    print(args,type(args))

 

func(1)

-->>

(1,) <class 'tuple'>

  

*args是可变参数,x,y已经又1,2传参,*args就得到3,4。

1

2

3

4

def func(x,y,*args):

    print(args,type(args))

 

func(1,2,3,4)

  

**kwargs的使用方法

      **kwargs 打包关键字参数成dict给函数体调用

 

参数被打包成了一个字典

1

2

3

4

5

6

def func(**kwargs):

    print(kwargs,type(kwargs))

 

func(a=2,b=2)

-->>

{'a'2'b'2} <class 'dict'>

  

常见的用法:

1

2

3

4

5

6

7

8

9

10

def test(data,**kwargs):

    instance = kwargs.pop('instance',False)

    context = kwargs.pop('context',{})

    print(data,instance,context)

 

test(data='xxx', instance=True)

-->

xxx True {}

#有一个固定参数data

#剩下的是选择性传参的kv对,如果没有传这个参数,就使用pop设定默认值。

  

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值