如何将关键字参数作为参数传递给函数?

如何将关键字参数作为参数传递给函数?

问题描述:

说我有一个这样定义的函数:

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")

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.

在函数定义中,标记为*的参数将接收所有与其他声明的参数都不对应的位置参数的元组,标记为**的参数将接收所有不包含其他关键字参数的字典的字典. t与其他声明的参数相对应.

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.