python - 为什么不能这样使用star运算符? def foo(* args,此=“default”,** kwargs)

标签 python python-2.7 syntax arguments syntax-error

这会很有趣:

def foo(*args, this="default", **kwargs):
    pass



  File "foo.py", line 1
    def foo(*args, this="default", **kwargs):
                  ^
SyntaxError: invalid syntax

由于我有一组不可知的位置参数,一组不可知的关键字参数以及一个或两个已知的关键字参数,因此我的另一种选择是:

def foo(*args, **kwargs):
    this = kwargs.pop("this", "default")
    ...

因此,由于似乎总是有一个很好的答案来说明为什么事情是这样,所以我想知道。为什么不允许这样做?

编辑:
谢谢@dano
Added in Python3

最佳答案

您想对this进行的操作是使其成为仅关键字的参数;没有办法提供位置参数。支持此功能是在Python 3.0中添加的。 Here是描述其添加以及其他相关增强的PEP。基本原理部分非常清楚地描述了该问题:

The current Python function-calling paradigm allows arguments to be specified either by position or by keyword. An argument can be filled in either explicitly by name, or implicitly by position.

There are often cases where it is desirable for a function to take a variable number of arguments. The Python language supports this using the 'varargs' syntax ('*name'), which specifies that any 'left over' arguments be passed into the varargs parameter as a tuple.

One limitation on this is that currently, all of the regular argument slots must be filled before the vararg slot can be.

This is not always desirable. One can easily envision a function which takes a variable number of arguments, but also takes one or more 'options' in the form of keyword arguments. Currently, the only way to do this is to define both a varargs argument, and a 'keywords' argument (**kwargs), and then manually extract the desired keywords from the dictionary.



基本上,这只是对varargs原始实现的限制,直到python 3才解决。

关于python - 为什么不能这样使用star运算符? def foo(* args,此=“default”,** kwargs),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24966614/

相关文章:

python - 在 Sympy 中使用抽象数学运算符/对象

python - Pyo server.boot() 在 Ubuntu 14.04 上因 pyolib._core.PyoServerStateException 而失败

Python 类继承 - 如何使用它连接到 mysql 数据库

c - C 中 char 数组的 if 语句

perl - 菱形算子在解析和裸词中的语法混淆

Mysql计数时得到零值

python - 从 C+ 生成 TFRecord 格式数据

python - 国际化 - Python MySQLDb 和 ISO-8859-7

python - 如何使用资源模块来衡量一个函数的运行时间?

python - 如何确保在首先调用另一个类函数之前不会调用一个类函数?