带有 *args 和 **kwargs 的默认参数 [英] Default arguments with *args and **kwargs

查看:43
本文介绍了带有 *args 和 **kwargs 的默认参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Python 2.x(我使用 2.7)中,这是在 *args**kwargs 中使用默认参数的正确方法>?
我发现了一个与此主题相关的 SO 问题,但这是针对 Python 3 的:
使用 *args 调用 Python 函数,**kwargs 和可选/默认参数

In Python 2.x (I use 2.7), which is the proper way to use default arguments with *args and **kwargs?
I've found a question on SO related to this topic, but that is for Python 3:
Calling a Python function with *args,**kwargs and optional / default arguments

那里,他们说这种方法有效:

There, they say this method works:

def func(arg1, arg2, *args, opt_arg='def_val', **kwargs):
    #...

在 2.7 中,它会导致 SyntaxError.有没有推荐的方法来定义这样的函数?
我是这样工作的,但我想有一个更好的解决方案.

In 2.7, it results in a SyntaxError. Is there any recommended way to define such a function?
I got it working this way, but I'd guess there is a nicer solution.

def func(arg1, arg2, *args, **kwargs):
    opt_arg ='def_val'
    if kwargs.__contains__('opt_arg'):
        opt_arg = kwargs['opt_arg']
    #...

推荐答案

只需将默认参数放在 *args 之前:

Just put the default arguments before the *args:

def foo(a, b=3, *args, **kwargs):

现在,如果您将 b 作为关键字参数或第二个位置参数传递,它将被显式设置.

Now, b will be explicitly set if you pass it as a keyword argument or the second positional argument.

示例:

foo(x) # a=x, b=3, args=(), kwargs={}
foo(x, y) # a=x, b=y, args=(), kwargs={}
foo(x, b=y) # a=x, b=y, args=(), kwargs={}
foo(x, y, z, k) # a=x, b=y, args=(z, k), kwargs={}
foo(x, c=y, d=k) # a=x, b=3, args=(), kwargs={'c': y, 'd': k}
foo(x, c=y, b=z, d=k) # a=x, b=z, args=(), kwargs={'c': y, 'd': k}

请注意,特别是 foo(x, y, b=z) 不起作用,因为在这种情况下 b 是按位置分配的.

Note that, in particular, foo(x, y, b=z) doesn't work because b is assigned by position in that case.

此代码也适用于 Python 3.将默认 arg after *args 放在 Python 3 中使其成为仅关键字"只能由名称指定的参数,不能由位置指定.如果您想在 Python 2 中使用仅关键字参数,您可以使用 @mgilson 的解决方案.

This code works in Python 3 too. Putting the default arg after *args in Python 3 makes it a "keyword-only" argument that can only be specified by name, not by position. If you want a keyword-only argument in Python 2, you can use @mgilson's solution.

这篇关于带有 *args 和 **kwargs 的默认参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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