使用命名参数作为参数传递函数

2024-09-29 19:33:45 发布

您现在位置:Python中文网/ 问答频道 /正文

我按照这个方法传递函数作为参数:

Passing functions with arguments to another function in Python?

然而,我无法理解如何将函数本身的参数作为names参数传递

def retry(func, *args):
  func(*args)

def action(args):
  do something

retry(action, arg1, namedArg=arg2)

这里我有个例外:

^{pr2}$

通常,我可以:

action(arg1, namedArg=arg2)

请帮忙/


Tags: 方法参数defwithargsaction传递函数functions
3条回答

读这个,keyword arguments in python doc。在

因为错误清楚地指出got an unexpected keyword argument 'namedArg'。其中,as只提供*args中的参数。在

你会发现很多例子来理解关键字参数。在

*args及其同级的**kwargs是通常用于额外参数和关键字参数的名称。传递namedArg=arg2时传递的是一个kew-word参数。在

所以,试试这个:

def retry(func, *args, **kwargs):
  func(*args, **kwargs)

def action(*args, **kwargs):
  do something

retry(action, arg1, namedArg=arg2)

如果你用

^{pr2}$

然后您将得到args作为参数列表,kwargs作为关键字参数字典,因此在您的例子中

args = [arg1]
kwargs = {'namedArg':arg2}

你需要的是函数工具。在

http://docs.python.org/2/library/functools.html#functools.partial

from functools import partial

def action(arg):
    do something

def action2(arg=1):
    do something

def action3(arg1, arg2=2):
    do something

partial(action, arg1)

partial(action, arg1, arg2=3)

相关问题 更多 >

    热门问题