gpt4 book ai didi

python - **(双星/星号)和*(星/星号)对参数有何作用?

转载 作者:太空宇宙 更新时间:2023-11-03 21:39:00 28 4
gpt4 key购买 nike

这些函数定义中的*args**kwargs是什么意思?

def foo(x, y, *args):
pass

def bar(x, y, **kwargs):
pass
<小时/>

参见What do ** (double star/asterisk) and * (star/asterisk) mean in a function call?关于参数的补充问题。

最佳答案

*args**kwargs 是一种常见的习惯用法,允许函数使用任意数量的参数,如 more on defining functions 部分所述。在 Python 文档中。

*args 将为您提供所有函数参数 as a tuple :

def foo(*args):
for a in args:
print(a)

foo(1)
# 1

foo(1,2,3)
# 1
# 2
# 3

**kwargs 将为您提供一切关键字参数,除了那些对应于作为字典的形式参数的参数。

def bar(**kwargs):
for a in kwargs:
print(a, kwargs[a])

bar(name='one', age=27)
# name one
# age 27

这两种习惯用法都可以与普通参数混合,以允许一组固定参数和一些可变参数:

def foo(kind, *args, **kwargs):
pass

也可以反过来使用:

def foo(a, b, c):
print(a, b, c)

obj = {'b':10, 'c':'lee'}

foo(100,**obj)
# 100 10 lee

*l 习语的另一种用法是在调用函数时解压参数列表

def foo(bar, lee):
print(bar, lee)

l = [1,2]

foo(*l)
# 1 2

在 Python 3 中,可以在赋值的左侧使用 *l ( Extended Iterable Unpacking ),尽管在这种情况下它给出的是列表而不是元组:

first, *rest = [1,2,3,4]
first, *l, last = [1,2,3,4]

Python 3 还添加了新的语义(请参阅 PEP 3102 ):

def func(arg1, arg2, arg3, *, kwarg1, kwarg2):
pass

例如,以下内容在 python 3 中有效,但在 python 2 中无效:

>>> x = [1, 2]
>>> [*x]
[1, 2]
>>> [*x, 3, 4]
[1, 2, 3, 4]

>>> x = {1:1, 2:2}
>>> x
{1: 1, 2: 2}
>>> {**x, 3:3, 4:4}
{1: 1, 2: 2, 3: 3, 4: 4}

此类函数仅接受 3 个位置参数,并且 * 之后的所有内容只能作为关键字参数传递。

注意:

  • Python dict,语义上用于关键字参数传递,是任意排序的。但是,在 Python 3.6 中,保证关键字参数记住插入顺序。
  • **kwargs 中的元素顺序现在对应于关键字参数传递给函数的顺序。” -What’s New In Python 3.6
  • 事实上,CPython 3.6 中的所有字典都会记住插入顺序作为实现细节,这在 Python 3.7 中成为标准。

关于python - **(双星/星号)和*(星/星号)对参数有何作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53028374/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com