【问题标题】:What does a star * alone mean in a function declaration? [duplicate]函数声明中单独的星 * 是什么意思? [复制]
【发布时间】:2015-12-20 00:58:38
【问题描述】:

以下代码中的* 是什么意思(可在pprint 库中找到)?

def pformat(object, indent=1, width=80, depth=None, *, compact=False):
    """Format a Python object into a pretty-printed representation."""
    return PrettyPrinter(indent=indent, width=width, depth=depth,
                         compact=compact).pformat(object)

如果是*args,那么它将是任意数量的位置参数。参数值将在名为args 的元组中。前4个参数可以按名称或位置分配,参数compact只能按名称分配...

好吧,不!因为和the documentation不符:

在函数调用中,关键字参数必须跟在位置之后 论据。

那么,星号在其他命名参数之后和之前做了什么?以及它是如何使用的?或者不使用为什么会存在?

【问题讨论】:

    标签: python syntax parameter-passing


    【解决方案1】:

    当没有可变参数时,它将位置参数与keyword-only arguments 分开。这是 Python-3 独有的功能。

    【讨论】:

    • 谢谢。在问题中我提到了 Python 2 文档页面,但引用的短语也在 3.
    猜你喜欢
    • 1970-01-01
    • 2011-03-09
    • 1970-01-01
    • 2019-10-23
    • 2011-04-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多