Python,可变长度位置参数后的默认关键字参数 [英] Python, default keyword arguments after variable length positional arguments

查看:178
本文介绍了Python,可变长度位置参数后的默认关键字参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我以为我可以在Python 2的函数调用中在变长位置参数之后使用命名参数,但是在导入python类时出现 SyntaxError 的问题。我正在使用以下获取方法进行编写,例如:

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

错误看起来像:

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)

等。

推荐答案

它确实有效,但仅在Python 3中有效。请参见PEP 3102 。浏览新功能文档后,似乎没有2.x反向移植,因此您很不走运。您必须接受任何关键字参数( ** kwargs )并手动对其进行解析。您可以使用 d.get(默认为k)来获取 d [k] 默认(如果不存在)。要从 kwargs 中删除​​参数,例如在调用超类方法之前,请使用 d.pop

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.

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

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

类似地,仅关键字参数不需要具有默认值。在 * args 参数之后是将它们标记为仅关键字,而不是默认值的地方:

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

这篇关于Python,可变长度位置参数后的默认关键字参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆