简体   繁体   English

Python一个将函数作为参数及其参数的函数

[英]Python A function that takes a function as a parameter with its parameters

Imagine I have a two functions 假设我有两个功能

def areaSquare(a,b):
   print( a * b)

def areaCircle(radius):
   print(3.14159 * radius ** 2)

And I want to create a third function that is called area. 我想创建第三个函数,称为Area。

area(areaCircle,radius = 3, repeat = 5)
# prints 3.14159 * 9 five times
area(areaSquare, a = 2, b = 3, repeat = 6)
# prints 2 * 6 six times

So the function takes a function as a parameter. 因此,该函数将函数作为参数。 Depending on the function which is passed to it as a parameter, it should require additional parameters. 根据作为参数传递给它的函数,它应该需要其他参数。 Is there a way to achieve this? 有没有办法做到这一点? I know function overloading would be an option. 我知道函数重载将是一个选择。 But I do not want to define multiple functions for this purpose. 但是我不想为此定义多个功能。

Yes, kwargs are your friend here. 是的, kwargs是您的朋友在这里。 We can define the function such that the remaining parameters are captured in a dictionary named kwargs , and then passed to the function we provide. 我们可以定义函数,以便将其余参数捕获在名为kwargs的字典中,然后传递给我们提供的函数。 Like: 喜欢:

def area(func, repeat, **kwargs):
    for _ in range(repeat):
        func(**kwargs)

So all parameters except func and repeat are stored in the kwargs dictionary, and later we call the func function (the first argument) with the named parameters. 因此,除funcrepeat以外的所有参数都存储在kwargs词典中,随后我们使用命名参数调用func函数(第一个参数)。

Note that this will not work (correctly) for functions that require a func and/or repeat parameter, since we capture these at the area function level. 请注意,这对于需要func和/或repeat参数的func将不会(正确)起作用,因为我们在area函数级别捕获了这些函数。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 调用 Python function 作为参数传递而不知道它是否需要任何参数 - Call Python function passed as parameter without knowing if it takes any parameters Python内省:函数所需参数的描述 - Python introspection: description of the parameters a function takes 减少函数在python中使用的参数数量 - Reducing the number of parameters a function takes in python Function 接受可选参数 - Function that takes in optional parameter 这个python函数如何获取其参数? - How does this python function get its parameters? 您如何为 function 编写名为 makeWordLengthDict 的程序,该程序将单词列表作为其唯一参数,并在 python 中返回字典 - how do you write a program for function named makeWordLengthDict which takes a LIST of words as its only parameter, and returns a dictionary in python Python-对象的参数及其值作为函数的参数 - Python - parameter of an object and its value as argument of a function 获取作为参数传递给python中函数的对象的参数 - Getting parameters of an object passed as parameter to a function in python 无法在python中调用类函数(TypeError:object()不带参数) - Can't call class function in python (TypeError: object() takes no parameters) 如何输入一个 function 以可调用对象及其参数作为参数 - 例如 function 的数值积分? - How to typehint a function which takes a callable and its args as parameters - e.g. a numerical integration of a function?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM