星号(*)作为python函数中的参数

时间:2018-12-15 20:37:01

标签: python

我在查看glob函数的定义,发现第二个参数就是*

def glob(pathname, *, recursive=False):
    """Return a list of paths matching a pathname pattern.
    [...]
    """
    return list(iglob(pathname, recursive=recursive))

*的意义是什么?

2 个答案:

答案 0 :(得分:8)

*指示位置参数的结尾。此后的每个参数只能由关键字指定。这是在PEP 3102

中定义的
>>> def foo1(a, b=None):
...     print(a, b)
...
>>> def foo2(a, *, b=None):
...     print(a, b)
...
>>> foo1(1, 2)
1 2
>>> foo2(1, 2)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: foo1() takes 1 positional argument but 2 were given
>>> foo2(1, b=2)
1 2

答案 1 :(得分:2)

*之后的所有参数都必须明确指定其名称。例如,如果您具有以下功能:

def somefunction(a,*,b):
    pass

您可以这样写:

somefunction(0, b=0)

但不是这样:

somefunction(0, 0)