Python:按名称和 kwargs 传递参数 [英] Python: Passing parameters by name along with kwargs

查看:29
本文介绍了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.

这篇关于Python:按名称和 kwargs 传递参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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