如何将关键字参数作为参数传递给函数? [英] How can I pass keyword arguments as parameters to a function?
问题描述
假设我有一个这样定义的函数:
Say I have a function defined thus:
def inner_func(spam, eggs):
# code
然后我想调用这样的函数:
I then want to call a function like this:
outer_func(spam=45, eggs="blah")
Inside outer_func
我希望能够使用传递给 outer_func
的完全相同的参数调用 inner_func
.
Inside outer_func
I want to be able to call inner_func
with exactly the same parameters that were passed into outer_func
.
这可以通过像这样编写 outer_func
来实现:
This can be achieved by writing outer_func
like this:
def outer_func(spam, eggs):
inner_func(spam, eggs)
但是,我希望能够更改 inner_func
接受的参数,并相应地更改我传递给 outer_func
的参数,但无需更改outer_func
每次.
However, I'd like to be able to change the arguments inner_func
takes, and change the parameters I pass to outer_func
accordingly, but without having to change anything in outer_func
each time.
有没有(简单的)方法可以做到这一点?请使用 Python 3.
Is there a (easy) way to do this? Python 3 please.
推荐答案
看起来您正在寻找 *
和 **
符号:
Looks like you're looking for the *
and **
notations:
def outer_func(*args, **kwargs):
inner_func(*args, **kwargs)
然后你可以做outer_func(1, 2, 3, a='x', b='y')
,outer_func
会调用inner_func(1, 2, 3, a='x', b='y')
.
Then you can do outer_func(1, 2, 3, a='x', b='y')
, and outer_func
will call inner_func(1, 2, 3, a='x', b='y')
.
如果您只想允许关键字参数,请删除 *args
.
If you only want to allow keyword arguments, drop the *args
.
在函数定义中,标有 *
的参数接收所有与其他声明参数不对应的位置参数的元组,以及标有 **
的参数> 接收与其他声明参数不对应的所有关键字参数的字典.
In a function definition, a parameter marked with *
receives a tuple of all positional arguments that didn't correspond to other declared parameters, and an argument marked with **
receives a dict of all keyword arguments that didn't correspond to other declared parameters.
在函数调用中,在序列(或其他可迭代)参数前加上 *
将其解包为单独的位置参数,并在映射参数前加上 **
将其解包成单独的关键字参数.
In a function call, prefixing a sequence (or other iterable) argument with *
unpacks it into separate positional arguments, and prefixing a mapping argument with **
unpacks it into separate keyword arguments.
这篇关于如何将关键字参数作为参数传递给函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!