Python中*和**的区别

Python中,(*)会把接收到的参数形成一个元组,而(**)则会把接收到的参数存入一个字典

 

我们可以看到,foo方法可以接收任意长度的参数,并把它们存入一个元组中

1

2

3

4

5

6

7

8

9

10

11

12

>>> def foo(*args):

...     print(args)

...

>>> foo("fruit""animal""human")

('fruit''animal''human')

>>> foo(12345)

(12345)

>>> arr = [12345]  # 如果我们希望将一个数组形成元组,需要在传入参数的前面 加上一个*

>>> foo(arr)

([12345],)

>>> foo(*arr)

(12345)

  

(**)将接收到的参数存入一个字典

1

2

3

4

5

6

7

8

>>> def foo(**kwargs):

...     for key, value in kwargs.items():

...         print("%s=%s" % (key, value))

...

>>> foo(a=1, b=2, c=3)

a=1

b=2

c=3

 

(*)和(**)一起使用 

1

2

3

4

5

6

7

8

9

10

11

>>> def foo(*args, **kwargs):

...     print("args:", args)

...     print("kwargs:", kwargs)

...

>>> foo(123, a=1, b=2)

args: (123)

kwargs: {'a'1'b'2}

>>> arr = [123]

>>> foo(*arr, a=1, b=2)

args: (123)

kwargs: {'a'1'b'2}

  

name作为foo第一个参数,在调用foo("hello", 1, 2, 3, middle="world", a=1, b=2, c=3)方法时,自然而然捕获了hello,而middle必须经过指定关键字参数才可以捕获值,否则会和之前的参数一样形成一个元组

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

>>> def foo(name, *args, middle=None**kwargs):

...     print("name:", name)

...     print("args:", args)

...     print("middle:", middle)

...     print("kwargs:", kwargs)

...

>>> foo("hello"123, a=1, b=2, c=3)

name: hello

args: (123)

middle: None

kwargs: {'a'1'b'2'c'3}

>>> foo("hello"123, middle="world", a=1, b=2, c=3)

name: hello

args: (123)

middle: world

kwargs: {'a'1'b'2'c'3}

>>> my_foo = {"name""hello""middle""world""a""1""b""2""c""3"}

>>> foo(**my_foo)

name: hello

args: ()

middle: world

kwargs: {'a''1''b''2''c''3'}

  

此外,我们还可以定义一个字典my_foo,并以foo(**my_foo)这样的方式,让name和middle各自捕获自己的值,没有捕获的则存入一个字典

 

当我们删除my_foo中的name,再像之前传入函数,函数会报错说需要name这个参数

1

2

3

4

5

>>> del my_foo["name"]

>>> foo(**my_foo)

Traceback (most recent call last):

  File "<stdin>", line 1in <module>

TypeError: foo() missing 1 required positional argument: 'name'

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值