python 和 的区别_Python中*和**的区别

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

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

>>> def foo(*args):

... print(args)

...

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

('fruit', 'animal', 'human')

>>> foo(1, 2, 3, 4, 5)

(1, 2, 3, 4, 5)

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

>>> foo(arr)

([1, 2, 3, 4, 5],)

>>> foo(*arr)

(1, 2, 3, 4, 5)

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

>>> 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

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

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

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

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

...

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

args: (1, 2, 3)

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

>>> arr = [1, 2, 3]

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

args: (1, 2, 3)

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

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

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

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

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

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

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

...

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

name: hello

args: (1, 2, 3)

middle: None

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

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

name: hello

args: (1, 2, 3)

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这个参数

>>> del my_foo["name"]

>>> foo(**my_foo)

Traceback (most recent call last):

File "", line 1, in

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、付费专栏及课程。

余额充值