Python: Passing parameters by name along with kwargs(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):
...
这将允许使用 name 和 lname 作为关键字调用.
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 传递参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:Python:通过名称和 kwargs 传递参数
基础教程推荐
- 求两个直方图的卷积 2022-01-01
- 使用大型矩阵时禁止 Pycharm 输出中的自动换行符 2022-01-01
- PANDA VALUE_COUNTS包含GROUP BY之前的所有值 2022-01-01
- Plotly:如何设置绘图图形的样式,使其不显示缺失日期的间隙? 2022-01-01
- 包装空间模型 2022-01-01
- 在同一图形上绘制Bokeh的烛台和音量条 2022-01-01
- PermissionError: pip 从 8.1.1 升级到 8.1.2 2022-01-01
- 修改列表中的数据帧不起作用 2022-01-01
- 无法导入 Pytorch [WinError 126] 找不到指定的模块 2022-01-01
- 在Python中从Azure BLOB存储中读取文件 2022-01-01
