在函数的签名中,星号在不带标识符名称的情况下在Python中意味着什么?

ziy*_*ang 4 python

我知道的意思和用法*args。但是有时候没什么好比args*。例如,在函数中pprint

def pprint(object, stream=None, indent=1, width=80, depth=None, *,
           compact=False):
    """Pretty-print a Python object to a stream [default is sys.stdout]."""
    printer = PrettyPrinter(
        stream=stream, indent=indent, width=width, depth=depth,
        compact=compact)
    printer.pprint(object)
Run Code Online (Sandbox Code Playgroud)

*签名中有一个。这是什么意思?

jon*_*rpe 5

参数之后*关键字只。在* “吸收了”任何额外的位置参数,因此,如果您定义:

def foo(x, y, *, z):
    print(x, y, z)
Run Code Online (Sandbox Code Playgroud)

然后致电:

foo(1, 2, 3)
Run Code Online (Sandbox Code Playgroud)

将不起作用,因为没有z提供,并且仅期望两个位置参数:

>>> foo(1, 2, 3)
Traceback (most recent call last):
  File "<pyshell#2>", line 1, in <module>
    foo(1, 2, 3)
TypeError: foo() takes 2 positional arguments but 3 were given
Run Code Online (Sandbox Code Playgroud)

z 必须现在关键字提供:

>>> foo(1, 2, z=3)
1 2 3
Run Code Online (Sandbox Code Playgroud)

可以使用标准方法执行此操作*args,但是使用*可以清楚地表明,您不需要任何其他位置参数,并且如果在末尾有任何错误,则会引发错误*。正如PEP所说:

第二个语法更改是允许为varargs自变量省略自变量名称。这样做的含义是允许将仅关键字参数用作不会采用varargs参数的函数