使用 **kwargs 将 **kwargs 参数传递给另一个函数 [英] pass **kwargs argument to another function with **kwargs

查看:67
本文介绍了使用 **kwargs 将 **kwargs 参数传递给另一个函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不明白下面的例子,假设我有这些功能:

I do not understand the following example, let's say I have these functions:

# python likes
def save(filename, data, **kwargs):
    fo = openX(filename, "w", **kwargs) # <- #1
    fo.write(data)
    fo.close()
# python doesnt like
def save2(filename, data, **kwargs):
    fo = openX(filename, "w", kwargs) # <- #2
    fo.write(data)
    fo.close()

def openX(filename, mode, **kwargs):
    #doing something fancy and returning a file object

为什么#1 是正确的解决方案而#2 是错误的解决方案?**kwargs 基本上是一个 dict,所以如果我想将参数传递给 openX,我认为正确的方法是没有 ** 并且只给出 dict.但是 Python 显然不喜欢第二个参数,并告诉我我给出了 3 个而不是 2 个参数.

Why is #1 the right solution and #2 the wrong one? **kwargs is basically a dict, so if I want to pass down the argument to openX I think the correct way would be without ** and just giving the dict. But Python obviously doesn't like the second one and tells me I gave 3 instead of 2 arguments.

这背后的原因是什么?

推荐答案

在第二个示例中,您提供 3 个参数:文件名、模式和字典 (kwargs).但是 Python 需要:2 个形式参数加上关键字参数.

In the second example you provide 3 arguments: filename, mode and a dictionary (kwargs). But Python expects: 2 formal arguments plus keyword arguments.

通过在字典前加上 '**' 前缀,您可以将字典 kwargs 解包为关键字参数.

By prefixing the dictionary by '**' you unpack the dictionary kwargs to keywords arguments.

字典(类型 dict)是包含键值对的单个变量.

A dictionary (type dict) is a single variable containing key-value pairs.

关键字参数"是键值方法参数.

"Keyword arguments" are key-value method-parameters.

任何字典都可以通过在函数调用期间以 ** 为前缀来解压为关键字参数.

Any dictionary can by unpacked to keyword arguments by prefixing it with ** during function call.

这篇关于使用 **kwargs 将 **kwargs 参数传递给另一个函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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