Python:通过名称和kwargs一起传递参数 [英] Python: Passing parameters by name along with kwargs
问题描述
def myFun1(one ='1',two ='2'):
...
然后我们可以调用函数并按名称传递参数:
myFun1(two ='two',one ='one')
我们也可以这样做:
def myFun2(** kwargs):
print kwargs.get('one','nothing here')
myFun2(所以我想知道是否有可能将两种方法结合起来:
def myFun3(name,lname,** other_info):
...
一般情况下我们可以做什么样的组合? 感谢和抱歉我这个愚蠢的问题 myFun3(lname ='Someone',name ='myName',city ='cityName',otherInfo ='blah')$ c
总体思路是:
def func(arg1,arg2,...,kwarg1 = default,kwarg2 = default,...,* args,** kwargs):
。 ..
您可以使用尽可能多的那些。 *
和 **
会'吸收'任何剩余的价值,否则不会说明。
位置参数(不带默认值提供)不能由关键字给出,非默认参数不能跟在默认参数后面。
注意Python 3还增加了通过在 *
之后指定关键字参数的功能:
def func(arg1,arg2,* args,kwonlyarg = default):
...
您也可以单独使用 *
( def func(a1,a2,*,kw = d) code>)这意味着没有参数被捕获,但之后的任何参数都是关键字。
因此,如果你在3.x中,你可以产生你想要的行为:
def myFun3(*,name,lname,** other_info):
.. 。
这可以通过 name
进行调用, lname
作为关键字。
请注意,这是一个联合国通常的界面,这可能会让用户恼火 - 我只会在非常具体的用例中使用它。
在2.x中,您需要手动创建解析 ** kwargs
。
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
The general idea is:
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.
Note Python 3 also adds the ability to specify keyword-only arguments by having them after *
:
def func(arg1, arg2, *args, kwonlyarg=default):
...
You can also use *
alone (def func(a1, a2, *, kw=d):
) which means that no arguments are captured, but anything after is keyword-only.
So, if you are in 3.x, you could produce the behaviour you want with:
def myFun3(*, name, lname, **other_info):
...
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.
In 2.x, you would need to manually make this by parsing **kwargs
.
这篇关于Python:通过名称和kwargs一起传递参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!