Python: 返回运行给定函数 n 次的函数

Python: Returning a function that runs a given function n times

我正在尝试编写一个将函数作为其参数的函数,并且 return 是一个运行该函数给定次数的新函数。

例如,如果我有一个函数:

def doubleNumber(num):
    return num * 2

我做了以下事情:

doubleThrice = repeatFunction(doubleNumber, 3)

然后我应该得到这个:

doubleThrice(3) # Returns 18 but should it?

到目前为止我有这个,但我不认为它在做我想要的:

def repeatFunction(func, n):
    def inner(inp):
        return func(inp) * n
    return inner

我的印象是它只是 运行 函数一次,然后将结果乘以 n,而不是 运行 函数 n 次,虽然我不确定。

我只是想不出如何在 repeatFunction 函数和 return 中构建我需要的函数,也没有任何在线帮助对我来说真正有意义。

如果您想多次应用一个函数,您可能需要一个重复那么多次的循环:

def repeatFunction(func, n):
    def inner(inp):
        for i in range(n):
            inp = func(inp)
        return inp
    return inner