双星号(**)和星号(*)在参数中的作用是什么?

3351

14
请参考以下链接:https://dev59.com/0mw05IYBdhLWcg3w41sp - Russia Must Remove Putin
159
这个问题是一个非常受欢迎的重复目标,但不幸的是,它经常被错误地使用。请记住,这个问题询问如何使用可变参数定义函数(def func(*args))。如果你想要了解在函数调用func(*[1,2]) 表示什么,请参见 这里。如果你想了解如何展开参数列表,请参见 这里。如果你想了解在 字面量 中 ([*[1, 2]]) * 的含义,请参见 这里 - Aran-Fey
4
我认为"What does it mean in function calls"的更好翻译应该是"在函数调用中星号操作符的含义是什么?",而不是你提供的链接"https://dev59.com/wG435IYBdhLWcg3wvyw5"。这个链接并没有真正回答`**`的使用,而且它的问题范围更窄。 - ShadowRanger
1
这个问题 - 像许多非常古老的问题一样 - 有点反向; 通常一个问题应该是关于如何解决新代码中的问题,而不是如何理解现有代码。对于后者,如果您要将其他内容视为重复项,请考虑 https://dev59.com/VnI-5IYBdhLWcg3wKE6x(尽管这仅涵盖 * 而不是 **)。 - Karl Knechtel
我在https://youtu.be/sYeqpnAA7U4中使用星号运算符解释了解包。 - Dr Nisha Arora
显示剩余2条评论
28个回答

3188
*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, bar=None, **kwargs):
    print(kind, args, bar, kwargs)

foo(123, 'a', 'b', apple='red')
# 123 ('a', 'b') None {'apple': 'red'}

也可以反过来使用这个。
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)

baz = [1, 2]

foo(*baz)
# 1 2

在Python 3中,可以在赋值的左侧使用*l扩展可迭代解包),尽管在这种情况下它返回的是一个列表而不是元组。
first, *rest = [1, 2, 3, 4]
# first = 1
# rest = [2, 3, 4]

此外,Python 3 还添加了一个新的语义(参见PEP 3102):
def func(arg1, arg2, arg3, *, kwarg1, kwarg2):
    pass

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

注意:

用于关键字参数传递的Python dict在语义上是任意排序的。然而,在Python 3.6+中,关键字参数保证记住插入顺序。 “**kwargs中元素的顺序现在与传递给函数的关键字参数的顺序相对应。” - Python 3.6中的新功能。 实际上,CPython 3.6中的所有dict都会以插入顺序记住,这在Python 3.7中成为标准。


822

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

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'

218

单个星号 * 表示可以有任意数量的额外位置参数。可以像 foo(1,2,3,4,5) 这样调用 foo()。在 foo() 函数体中,param2 是一个包含 2-5 的序列。

双星号 ** 表示可以有任意数量的额外命名参数。可以像 bar(1, a=2, b=3) 这样调用 bar()。在 bar() 函数体中,param2 是一个包含 {'a':2, 'b':3} 的字典。

使用以下代码:

def foo(param1, *param2):
    print(param1)
    print(param2)

def bar(param1, **param2):
    print(param1)
    print(param2)

foo(1,2,3,4,5)
bar(1,a=2,b=3)

输出结果为

1
(2, 3, 4, 5)
1
{'a': 2, 'b': 3}

212

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

它们允许定义函数以接受和用户传递任意数量的参数,包括位置参数(*)和关键字参数(**)。

定义函数

*args 允许传入任意数量的可选位置参数(参数),这些参数将被分配给名为 args 的元组。

**kwargs 允许传入任意数量的可选关键字参数(参数),这些参数将在名为 kwargs 的字典中。

您可以(并且应该)选择任何合适的名称,但是如果参数的语义不明确,则 argskwargs 是标准名称。

扩展,传递任意数量的参数

您还可以使用 *args**kwargs 从列表(或任何可迭代对象)和字典(或任何映射)中传递参数。

接收参数的函数不必知道它们正在被扩展。

例如,Python 2 的 xrange 并没有明确期望 *args,但由于它需要 3 个整数作为参数:

>>> x = xrange(3) # create our *args - an iterable of 3 integers
>>> xrange(*x)    # expand here
xrange(0, 2, 2)

作为另一个示例,我们可以在str.format中使用字典扩展:
>>> foo = 'FOO'
>>> bar = 'BAR'
>>> 'this is foo, {foo} and bar, {bar}'.format(**locals())
'this is foo, FOO and bar, BAR'

Python 3的新特性:使用关键字参数定义函数

关键字参数可以在*args之后使用,例如,在这个例子中,kwarg2必须作为关键字参数给出,不能按位置给出:

def foo(arg, kwarg=None, *args, kwarg2=None, **kwargs): 
    return arg, kwarg, args, kwarg2, kwargs

使用方法:

>>> foo(1,2,3,4,5,kwarg2='kwarg2', bar='bar', baz='baz')
(1, 2, (3, 4, 5), 'kwarg2', {'bar': 'bar', 'baz': 'baz'})

此外,* 可以单独使用,表示只有关键字参数可用,不允许无限制的位置参数。
def foo(arg, kwarg=None, *, kwarg2=None, **kwargs): 
    return arg, kwarg, kwarg2, kwargs

这里,kwarg2 必须再次作为显式命名的关键字参数传入:
>>> foo(1,2,kwarg2='kwarg2', foo='foo', bar='bar')
(1, 2, 'kwarg2', {'foo': 'foo', 'bar': 'bar'})

由于我们没有*args*,因此不能再接受无限定位参数:

>>> foo(1,2,3,4,5, kwarg2='kwarg2', foo='foo', bar='bar')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: foo() takes from 1 to 2 positional arguments 
    but 5 positional arguments (and 1 keyword-only argument) were given

再次强调,这里需要通过名称而不是位置来指定 kwarg 参数:

def bar(*, kwarg=None): 
    return kwarg

在这个例子中,我们可以看到如果我们试图将 kwarg 作为位置参数传递,就会出现错误:
>>> bar('kwarg')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: bar() takes 0 positional arguments but 1 was given

我们必须将kwarg参数作为关键字参数显式传递。
>>> bar(kwarg='kwarg')
'kwarg'

Python 2 兼容演示

*args(通常称为“星号参数”)和 **kwargs(通过称为“关键字星号参数”可以省略星号,但是请明确使用“双星号 kwargs”)是 Python 的常用惯用语,用于使用 *** 符号。这些特定的变量名称不是必需的(例如,您可以使用 *foos**bars),但是偏离传统可能会激怒您的 Python 同事。

当我们不知道函数将接收什么或我们可能要传递多少个参数时,通常会使用它们,有时甚至在命名每个变量单独处理变得非常混乱和冗长时也会使用(但这是情况通常显式比隐式更好)。

示例 1

以下函数描述了它们如何使用,并展示了其行为。请注意,第一个带名字的 b 参数将在冒号之前由第二个位置参数使用:

def foo(a, b=10, *args, **kwargs):
    '''
    this function takes required argument a, not required keyword argument b
    and any number of unknown positional arguments and keyword arguments after
    '''
    print('a is a required argument, and its value is {0}'.format(a))
    print('b not required, its default value is 10, actual value: {0}'.format(b))
    # we can inspect the unknown arguments we were passed:
    #  - args:
    print('args is of type {0} and length {1}'.format(type(args), len(args)))
    for arg in args:
        print('unknown arg: {0}'.format(arg))
    #  - kwargs:
    print('kwargs is of type {0} and length {1}'.format(type(kwargs),
                                                        len(kwargs)))
    for kw, arg in kwargs.items():
        print('unknown kwarg - kw: {0}, arg: {1}'.format(kw, arg))
    # But we don't have to know anything about them 
    # to pass them to other functions.
    print('Args or kwargs can be passed without knowing what they are.')
    # max can take two or more positional args: max(a, b, c...)
    print('e.g. max(a, b, *args) \n{0}'.format(
      max(a, b, *args))) 
    kweg = 'dict({0})'.format( # named args same as unknown kwargs
      ', '.join('{k}={v}'.format(k=k, v=v) 
                             for k, v in sorted(kwargs.items())))
    print('e.g. dict(**kwargs) (same as {kweg}) returns: \n{0}'.format(
      dict(**kwargs), kweg=kweg))

我们可以使用help(foo)查看函数签名的在线帮助文档,它会告诉我们:
foo(a, b=10, *args, **kwargs)

让我们使用foo(1, 2, 3, 4, e=5, f=6, g=7)来调用此函数,它会打印出:
a is a required argument, and its value is 1
b not required, its default value is 10, actual value: 2
args is of type <type 'tuple'> and length 2
unknown arg: 3
unknown arg: 4
kwargs is of type <type 'dict'> and length 3
unknown kwarg - kw: e, arg: 5
unknown kwarg - kw: g, arg: 7
unknown kwarg - kw: f, arg: 6
Args or kwargs can be passed without knowing what they are.
e.g. max(a, b, *args) 
4
e.g. dict(**kwargs) (same as dict(e=5, f=6, g=7)) returns: 
{'e': 5, 'g': 7, 'f': 6}

示例2

我们还可以使用另一个函数来调用它,只需要提供a参数:

def bar(a):
    b, c, d, e, f = 2, 3, 4, 5, 6
    # dumping every local variable into foo as a keyword argument 
    # by expanding the locals dict:
    foo(**locals()) 

bar(100) 输出:

a is a required argument, and its value is 100
b not required, its default value is 10, actual value: 2
args is of type <type 'tuple'> and length 0
kwargs is of type <type 'dict'> and length 4
unknown kwarg - kw: c, arg: 3
unknown kwarg - kw: e, arg: 5
unknown kwarg - kw: d, arg: 4
unknown kwarg - kw: f, arg: 6
Args or kwargs can be passed without knowing what they are.
e.g. max(a, b, *args) 
100
e.g. dict(**kwargs) (same as dict(c=3, d=4, e=5, f=6)) returns: 
{'c': 3, 'e': 5, 'd': 4, 'f': 6}

例子3:装饰器的实际应用

好的,也许我们还没有看到它的实用性。那么想象一下,你有几个函数在不同iating代码之前和/或之后有冗余代码。以下命名函数仅为说明目的而使用伪代码。

def foo(a, b, c, d=0, e=100):
    # imagine this is much more code than a simple function call
    preprocess() 
    differentiating_process_foo(a,b,c,d,e)
    # imagine this is much more code than a simple function call
    postprocess()

def bar(a, b, c=None, d=0, e=100, f=None):
    preprocess()
    differentiating_process_bar(a,b,c,d,e,f)
    postprocess()

def baz(a, b, c, d, e, f):
    ... and so on

我们也许可以用不同的方法来处理这个问题,但是我们可以通过使用装饰器来消除冗余代码。下面的例子演示了如何使用*args**kwargs

def decorator(function):
    '''function to wrap other functions with a pre- and postprocess'''
    @functools.wraps(function) # applies module, name, and docstring to wrapper
    def wrapper(*args, **kwargs):
        # again, imagine this is complicated, but we only write it once!
        preprocess()
        function(*args, **kwargs)
        postprocess()
    return wrapper

现在每个包装函数都可以更加简洁地编写,因为我们已经消除了冗余:

@decorator
def foo(a, b, c, d=0, e=100):
    differentiating_process_foo(a,b,c,d,e)

@decorator
def bar(a, b, c=None, d=0, e=100, f=None):
    differentiating_process_bar(a,b,c,d,e,f)

@decorator
def baz(a, b, c=None, d=0, e=100, f=None, g=None):
    differentiating_process_baz(a,b,c,d,e,f, g)

@decorator
def quux(a, b, c=None, d=0, e=100, f=None, g=None, h=None):
    differentiating_process_quux(a,b,c,d,e,f,g,h)

通过将*args**kwargs因素化,我们可以减少代码行数,提高可读性和可维护性,并为程序中的逻辑提供唯一的规范位置。如果我们需要更改此结构的任何部分,则只需在一个地方进行每个更改。


66

首先让我们了解什么是位置参数和关键字参数。 下面是一个使用位置参数的函数定义示例。

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

test(1,2,3)
#output:
1
2
3

这是一个带有位置参数的函数定义。 你也可以使用关键字/命名参数来调用它:

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

test(a=1,b=2,c=3)
#output:
1
2
3

现在让我们来学习一个使用关键字参数的函数定义示例:

def test(a=0,b=0,c=0):
     print(a)
     print(b)
     print(c)
     print('-------------------------')

test(a=1,b=2,c=3)
#output :
1
2
3
-------------------------
你也可以使用位置参数调用此函数:
def test(a=0,b=0,c=0):
    print(a)
    print(b)
    print(c)
    print('-------------------------')

test(1,2,3)
# output :
1
2
3
---------------------------------

现在我们知道函数定义可以使用位置参数和关键字参数。

现在让我们来学习 '*' 运算符和 '**' 运算符。

请注意这些运算符可以在两个区域中使用:

a) 函数调用

b) 函数定义

函数调用中使用 '*' 运算符和 '**' 运算符。

让我们先看一个例子,然后再讨论它。

def sum(a,b):  #receive args from function calls as sum(1,2) or sum(a=1,b=2)
    print(a+b)

my_tuple = (1,2)
my_list = [1,2]
my_dict = {'a':1,'b':2}

# Let us unpack data structure of list or tuple or dict into arguments with help of '*' operator
sum(*my_tuple)   # becomes same as sum(1,2) after unpacking my_tuple with '*'
sum(*my_list)    # becomes same as sum(1,2) after unpacking my_list with  '*'
sum(**my_dict)   # becomes same as sum(a=1,b=2) after unpacking by '**' 

# output is 3 in all three calls to sum function.

所以请记住:

当在 函数调用 中使用 '*' 或 '**' 运算符时 -

'*'运算符会将数据结构(例如列表或元组)解包为函数定义所需的参数。

'**'运算符会将字典解包为函数定义所需的参数。

现在让我们研究在函数定义中使用 '*' 运算符的例子:

def sum(*args): #pack the received positional args into data structure of tuple. after applying '*' - def sum((1,2,3,4))
    sum = 0
    for a in args:
        sum+=a
    print(sum)

sum(1,2,3,4)  #positional args sent to function sum
#output:
10
在函数定义中,'*' 运算符将接收到的参数打包成一个元组。
现在让我们看一个 '**' 在函数定义中的使用示例:
def sum(**args): #pack keyword args into datastructure of dict after applying '**' - def sum({a:1,b:2,c:3,d:4})
    sum=0
    for k,v in args.items():
        sum+=v
    print(sum)

sum(a=1,b=2,c=3,d=4) #positional args sent to function sum
在函数定义中,'**' 运算符将收到的参数打包成一个字典。
因此请记住:
在函数调用中,'*' 将元组或列表的数据结构解包为位置或关键字参数,以便由函数定义接收。
在函数调用中,'**'将字典的数据结构解包为位置或关键字参数,以便由函数定义接收。
在函数定义中,'*' 将位置参数打包成元组。
在函数定义中,'**' 将关键字参数打包成字典。

1
这很容易理解。谢谢。对于来自Golang的人来说,列表/元组的打包/解包听起来类似于Golang中的可变参数:https://stackoverflow.com/a/23669857/6874596 - undefined
1
没问题,老板 我随时为您服务 :)我也喜欢Medu Vadaa :) 干杯 - undefined

47

这张表格对于在函数的构建调用中使用***非常方便:

            In function construction         In function call
=======================================================================
          |  def f(*args):                 |  def f(a, b):
*args     |      for arg in args:          |      return a + b
          |          print(arg)            |  args = (1, 2)
          |  f(1, 2)                       |  f(*args)
----------|--------------------------------|---------------------------
          |  def f(a, b):                  |  def f(a, b):
**kwargs  |      return a + b              |      return a + b
          |  def g(**kwargs):              |  kwargs = dict(a=1, b=2)
          |      return f(**kwargs)        |  f(**kwargs)
          |  g(a=1, b=2)                   |
-----------------------------------------------------------------------

这实际上只是总结了Lorin Hochstein的答案,但我发现它很有帮助。

相关地,星号/扩展运算符的用途已经在Python 3中扩展了。


1
显然,“splat”是代表星号“”的行话。http://www.catb.org/jargon/html/S/splat.html “在许多地方(包括DEC、IBM和其他公司)都使用这个名称来表示星号()字符(ASCII 0101010)。这可能源于早期线打印机上星号的“压扁虫”的外观。” - Moberg

37

TL;DR

这里介绍了Python编程中使用***的6个不同用例:

  1. 使用*args接受任意数量的位置参数: def foo(*args): pass,这里的foo接受任意数量的位置参数,即下列调用是有效的:foo(1)foo(1, 'bar')
  2. 使用**kwargs接受任意数量的关键字参数: def foo(**kwargs): pass,这里的foo接受任意数量的关键字参数,即下列调用是有效的:foo(name='Tom')foo(name='Tom', age=33)
  3. 使用*args, **kwargs接受任意数量的位置和关键字参数: def foo(*args, **kwargs): pass,这里的foo接受任意数量的位置和关键字参数,即下列调用是有效的:foo(1,name='Tom')foo(1, 'bar', name='Tom', age=33)
  4. 使用*强制使用关键字参数: def foo(pos1, pos2, *, kwarg1): pass,这里的*意味着foo只接受pos2后面的关键字参数,因此foo(1, 2, 3)会引发TypeError,但foo(1, 2, kwarg1=3)是可以的。
  5. 使用*_表示不再对更多位置参数感兴趣(注意:这只是一种惯例): def foo(bar, baz, *_): pass表示(按惯例)foo在其工作中只使用barbaz参数,并忽略其他参数。
  6. 使用**_表示不再对更多关键字参数感兴趣(注意:这只是一种惯例): def foo(bar, baz, **_): pass表示(按惯例)foo在其工作中只使用barbaz参数,并忽略其他参数。

BONUS:从Python 3.8开始,可以在函数定义中使用/来强制指定仅为位置参数。在以下示例中,参数a和b是位置参数,而c或d可以是位置或关键字参数,e或f必须是关键字参数:

def f(a, b, /, c, d, *, e, f):
    pass

BONUS 2: THIS ANSWER to the same question also brings a new perspective, where it shares what does * and ** means in a function call, functions signature, for loops, etc.


1
使用 / 的一个原因是它允许您更改函数中参数的名称,而不必更新调用函数的任何地方(您可以确保函数的任何调用者都没有使用参数名称来提供参数,因为它没有被使用)。 - Moberg

31

*** 在函数参数列表中有特殊用途。 * 表示该参数是一个列表,** 表示该参数是一个字典。这使得函数可以接受任意数量的参数。


26

如果你是通过例子来学习的!

  1. * 的目的是让你能够定义一个函数,它可以接受作为列表提供的任意数量的参数 (例如 f(*myList))。
  2. ** 的目的是让你能够通过提供一个字典来传递函数的参数 (例如 f(**{'x' : 1, 'y' : 2}))。

让我们通过定义一个函数来展示这个过程。这个函数接受两个普通变量 x, y,并且可以接受更多的参数作为 myArgs,还可以接受更多的参数作为 myKW。稍后,我们将展示如何使用 myArgDict 来传递 y 的值。

def f(x, y, *myArgs, **myKW):
    print("# x      = {}".format(x))
    print("# y      = {}".format(y))
    print("# myArgs = {}".format(myArgs))
    print("# myKW   = {}".format(myKW))
    print("# ----------------------------------------------------------------------")

# Define a list for demonstration purposes
myList    = ["Left", "Right", "Up", "Down"]
# Define a dictionary for demonstration purposes
myDict    = {"Wubba": "lubba", "Dub": "dub"}
# Define a dictionary to feed y
myArgDict = {'y': "Why?", 'y0': "Why not?", "q": "Here is a cue!"}

# The 1st elem of myList feeds y
f("myEx", *myList, **myDict)
# x      = myEx
# y      = Left
# myArgs = ('Right', 'Up', 'Down')
# myKW   = {'Wubba': 'lubba', 'Dub': 'dub'}
# ----------------------------------------------------------------------

# y is matched and fed first
# The rest of myArgDict becomes additional arguments feeding myKW
f("myEx", **myArgDict)
# x      = myEx
# y      = Why?
# myArgs = ()
# myKW   = {'y0': 'Why not?', 'q': 'Here is a cue!'}
# ----------------------------------------------------------------------

# The rest of myArgDict becomes additional arguments feeding myArgs
f("myEx", *myArgDict)
# x      = myEx
# y      = y
# myArgs = ('y0', 'q')
# myKW   = {}
# ----------------------------------------------------------------------

# Feed extra arguments manually and append even more from my list
f("myEx", 4, 42, 420, *myList, *myDict, **myDict)
# x      = myEx
# y      = 4
# myArgs = (42, 420, 'Left', 'Right', 'Up', 'Down', 'Wubba', 'Dub')
# myKW   = {'Wubba': 'lubba', 'Dub': 'dub'}
# ----------------------------------------------------------------------

# Without the stars, the entire provided list and dict become x, and y:
f(myList, myDict)
# x      = ['Left', 'Right', 'Up', 'Down']
# y      = {'Wubba': 'lubba', 'Dub': 'dub'}
# myArgs = ()
# myKW   = {}
# ----------------------------------------------------------------------

注意事项

  1. ** 仅适用于字典。
  2. 非可选参数赋值先执行。
  3. 您不能两次使用非可选参数。
  4. 如果适用,** 必须始终在 * 之后使用。

22

根据Python文档:

如果存在比形式参数槽更多的位置参数,则会引发TypeError异常,除非存在使用“*标识符”语法的形式参数;在这种情况下,该形式参数将接收一个包含超出位置参数(如果有)的元组(或者如果没有超出位置参数,则为空元组)。

如果任何关键字参数不对应于形式参数名称,则会引发TypeError异常,除非存在使用“**标识符”语法的形式参数;在这种情况下,该形式参数将接收一个包含超出关键字参数的字典(使用关键字作为键和参数值作为相应值),或者一个(新的)空字典,如果没有超出关键字参数。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接