python - 函数声明中单独的星号 * 是什么意思?

标签 python syntax parameter-passing

<分区>

以下代码中的* 是什么意思(在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 :

In a function call, keyword arguments must follow positional arguments.

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

最佳答案

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

关于python - 函数声明中单独的星号 * 是什么意思?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32727198/

相关文章:

python - 在c++中嵌入python时导入tensorflow返回null

python - 如何在 django View 中使用参数运行 scrapy 蜘蛛

python - 如何使用python关闭程序?

javascript - 我如何有条件地在 React 中的某些 HTML 中间包含标签

c# - C++/CLI 中 C# Array[] 的语法

python - 从 href 获取数据但它不可用

C#;在不单独声明方法的情况下创建一个新委托(delegate)?

bash - 将所有脚本参数复制到另一个变量

c++ - 将 QString 转换为 const void*

ios - Objective-C 通过引用传递与通过指针传递。有什么不同?为什么我们需要它?