[英]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. 因此,除func
和repeat
以外的所有参数都存储在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.