我想创建一个如下所示的包装器函数:
def functionWrapper(function, **kwargs):
"""
This function requires as input a function and a dictionary of named arguments for that function.
"""
results=function(**kwargs)
print results
def multiply(multiplicand1=0, multiplicand2=0):
return multiplicand1*multiplicand2
def main():
functionWrapper(
multiply,
{
'multiplicand1': 3,
'multiplicand2': 4,
}
)
if __name__ == "__main__":
main()
我在这个实现中遇到了困难:
TypeError: functionWrapper() takes exactly 1 argument (2 given)
我该如何解决这个问题?我在包装函数 function(**kwargs)
中使用任意函数是否合理?感谢您的帮助。
编辑:修复了字典规范中的错误
最佳答案
将字典项传递给该函数时使用**;
**{
'multiplicand1': 3,
'multiplicand2': 4,
}
输出:
12
正如@svk 在评论中指出的,functionWrapper
的 docstring 说:
This function requires as input a function and a dictionary of named arguments for that function.
所以在这种情况下,您需要将函数定义更改为:
def functionWrapper(function, kwargs):
并修正字典中的拼写错误,否则你将得到 0 作为答案:
'multiplicand1': 3,
'multiplicand1': 4, #Change this to 'multiplicand2
'
关于python - 如何在 Python 的包装函数中使用任意函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20426835/