Python:通过名称和 kwargs 传递参数

问题描述

在python中我们可以这样做:

In python we can do this:

def myFun1(one = '1', two = '2'):
    ...

然后我们可以调用函数并通过它们的名字传递参数:

Then we can call the function and pass the arguments by their name:

myFun1(two = 'two', one = 'one')

另外,我们可以这样做:

Also, we can do this:

def myFun2(**kwargs):
    print kwargs.get('one', 'nothing here')

myFun2(one='one')

所以我想知道是否可以将这两种方法结合起来,例如:

So I was wondering if it is possible to combine both methods like:

def myFun3(name, lname, **other_info):
    ...

myFun3(lname='Someone', name='myName', city='cityName', otherInfo='blah')

一般我们可以做哪些组合?

In general what combinations can we do?

感谢并为我的愚蠢问题感到抱歉.

Thanks and sorry for my silly question.


解决方案

大致思路是:

def func(arg1, arg2, ..., kwarg1=default, kwarg2=default, ..., *args, **kwargs):
    ...

您可以根据需要使用任意数量的这些.*** 将吸收"任何未以其他方式计算的剩余值.

You can use as many of those as you want. The * and ** will 'soak up' any remaining values not otherwise accounted for.

位置参数(没有默认提供)不能由关键字给出,非默认参数不能跟在默认参数之后.

Positional arguments (provided without defaults) can't be given by keyword, and non-default arguments can't follow default arguments.

注意 Python 3 还添加了通过在 * 之后指定仅关键字参数的功能:

Note Python 3 also adds the ability to specify keyword-only arguments by having them after *:

def func(arg1, arg2, *args, kwonlyarg=default):
    ...

您也可以单独使用 * (def func(a1, a2, *, kw=d):),这意味着不捕获任何参数,但之后的任何内容仅限关键字.

You can also use * alone (def func(a1, a2, *, kw=d):) which means that no arguments are captured, but anything after is keyword-only.

所以,如果你在 3.x 中,你可以产生你想要的行为:

So, if you are in 3.x, you could produce the behaviour you want with:

def myFun3(*, name, lname, **other_info):
    ...

这将允许使用 namelname 作为关键字调用.

Which would allow calling with name and lname as keyword-only.

请注意,这是一个不寻常的界面,可能会让用户感到烦恼 - 我只会在非常特定的用例中使用它.

Note this is an unusual interface, which may be annoying to the user - I would only use it in very specific use cases.

在 2.x 中,您需要手动解析 **kwargs.

In 2.x, you would need to manually make this by parsing **kwargs.

相关文章