\*\*(双星/星号)和\*(星号/星号)对参数有什么作用?

新手上路,请多包涵

*args**kwargs 是什么意思?

 def foo(x, y, *args):
def bar(x, y, **kwargs):

原文由 Todd 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 368
2 个回答

*args**kwargs 是一个常见的习惯用法,允许任意数量的函数参数,如 Python 文档中 关于定义函数的更多 部分所述。

*args 会给你所有的函数参数 作为一个元组

 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 中,可以在赋值的左侧使用 *lExtended 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 中的元素顺序现在对应于传递给函数的关键字参数的顺序。” - Python 3.6 的新功能
  • 事实上,CPython 3.6 中的所有 dicts 都会记住插入顺序作为实现细节,这在 Python 3.7 中成为标准。

原文由 Peter Hoffmann 发布,翻译遵循 CC BY-SA 4.0 许可协议

还值得注意的是,您也可以在调用函数时使用 *** 。这是一个快捷方式,允许您使用列表/元组或字典将多个参数直接传递给函数。例如,如果您具有以下功能:

 def foo(x,y,z):
    print("x=" + str(x))
    print("y=" + str(y))
    print("z=" + str(z))

您可以执行以下操作:

 >>> mylist = [1,2,3]
>>> foo(*mylist)
x=1
y=2
z=3

>>> mydict = {'x':1,'y':2,'z':3}
>>> foo(**mydict)
x=1
y=2
z=3

>>> mytuple = (1, 2, 3)
>>> foo(*mytuple)
x=1
y=2
z=3

注意: mydict 中的键的命名必须与函数 foo 的参数完全相同。否则它会抛出 TypeError

 >>> mydict = {'x':1,'y':2,'z':3,'badnews':9}
>>> foo(**mydict)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: foo() got an unexpected keyword argument 'badnews'

原文由 Lorin Hochstein 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题