Python,可变长度位置参数之后的默认关键字参数

发布于 2024-11-06 04:05:02 字数 626 浏览 0 评论 0原文

我以为我可以在 Python 2 中的函数调用中的可变长度位置参数之后使用命名参数,但在导入 python 类时出现 SyntaxError 。我正在使用以下“get”方法编写,例如:

class Foo(object):
    def __init__(self):
        print "You have created a Foo."

    def get(self, *args, raw=False, vars=None):
        print len(args)
        print raw
        print vars

错误看起来像:

def get(self, *args, raw=False, vars=None):
                     ^
SyntaxError: invalid syntax

我希望能够通过多种方式调用该方法:

f = Foo()
f.get(arg1, arg2)
f.get(arg1, raw=True)
f.get(arg1, arg2, raw=True, vars=something)

等等。

I thought I could use named parameters after variable-length positional parameters in a function call in Python 2, but I get a SyntaxError when importing a python class. I'm writing with the following "get" method, for example:

class Foo(object):
    def __init__(self):
        print "You have created a Foo."

    def get(self, *args, raw=False, vars=None):
        print len(args)
        print raw
        print vars

The error looks like:

def get(self, *args, raw=False, vars=None):
                     ^
SyntaxError: invalid syntax

I'd like to be able to call the method several ways:

f = Foo()
f.get(arg1, arg2)
f.get(arg1, raw=True)
f.get(arg1, arg2, raw=True, vars=something)

etc.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

浪菊怪哟 2024-11-13 04:05:02

它确实有效,但仅限于 Python 3。请参阅 PEP 3102。从浏览“新增内容”文档来看,似乎没有 2.x 向后移植,所以你运气不好。您必须接受任何关键字参数 (**kwargs) 并手动解析它。您可以使用 d.get(k, default) 来获取 d[k] 或 default(如果不存在)。要从kwargs 中删除参数,例如在调用超类的方法之前,请使用d.pop


请注意,在 def get(self, *args, raw=False, vars=None): 中,raw=Falsevars=None与关键字参数无关。这些是默认参数值。具有默认值的参数可以按位置传递,没有默认值的参数可以通过关键字传递:

def f(a=1): pass
f(2)  # works, passing a positionally
def f(a): pass
f(a=2)  # works, passing a by keyword

同样,仅关键字参数不需要具有默认值。在 *args 参数之后将它们标记为仅关键字,而不是存在默认值:

def f(*args, a): pass
# a is a mandatory, keyword-only argument

It does work, but only in Python 3. See PEP 3102. From glancing over the "what's new" documents, it seems that there is no 2.x backport, so you're out of luck. You'll have to accept any keyword arguments (**kwargs) and manually parse it. You can use d.get(k, default) to either get d[k] or default if that's not there. To remove an argument from kwargs, e.g. before calling a super class' method, use d.pop.


Note that in def get(self, *args, raw=False, vars=None):, the raw=False and vars=None have nothing to do with keyword arguments. Those are default argument values. Arguments with a default value may be passed positionally, and arguments without a default value may be passed by keyword:

def f(a=1): pass
f(2)  # works, passing a positionally
def f(a): pass
f(a=2)  # works, passing a by keyword

Similarly, keyword-only arguments are not required to have a default value. Coming after the *args argument is what marks them as keyword-only, not the presence of a default value:

def f(*args, a): pass
# a is a mandatory, keyword-only argument
北渚 2024-11-13 04:05:02

Python 的语法不允许函数和关键字参数中的变量参数同时具有默认值。如果您必须拥有关键字参数以及任意数量的位置参数,则还需要允许任意数量的关键字参数。

这是为关键字参数提供默认值以及允许任意数量的位置参数的常见模式:

def foo(*args, **kwargs):
   raw = kwargs.pop('raw', False)
   vars = kwargs.pop('vars', None)

如果您根本不使用额外的关键字参数,则无需担心。这使得该函数的自文档化程度较低,您可以通过正确编写的文档字符串来弥补。

Python's syntax doesn't allow variable args in function and keyword arguments with default value at the same time. If you must have keyword arguments along with arbitrary number of positional arguments, you need to allow arbitrary number of keyword arguments as well.

This is a common pattern to provide default values for keyword arguments, as well as allowing any number of positional arguments:

def foo(*args, **kwargs):
   raw = kwargs.pop('raw', False)
   vars = kwargs.pop('vars', None)

If you don't use the extra keyword arguments at all, you have nothing to worry about. This makes the function a bit less self-documenting, which you can make up with a properly written docstring.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文