我如何编写一个返回另一个函数的函数?

我如何编写一个返回另一个函数的函数?

问题描述:

在Python中,我想写一个函数 make_cylinder_volume(r),它返回另一个函数。返回的函数应该可以用参数 h 来调用,并返回高度为 h 和半径 r 。

In Python, I'd like to write a function make_cylinder_volume(r) which returns another function. That returned function should be callable with a parameter h, and return the volume of a cylinder with height h and radius r.

我知道如何从Python中的函数返回我返回另一个函数

I know how to return values from functions in Python, but how do I return another function?

b

Try this, using Python:

import math
def make_cylinder_volume_func(r):
    def volume(h):
        return math.pi * r * r * h
    return volume

像这样使用它,例如用 radius = 10 height = 5

Use it like this, for example with radius=10 and height=5:

volume_radius_10 = make_cylinder_volume_func(10)
volume_radius_10(5)
=> 1570.7963267948967

注意,返回一个函数很简单,就是在函数内部定义一个新函数,然后返回它最后 - 谨慎地为每个功能传递适当的参数。仅供参考,从另一个函数返回函数的技术称为 currying

Notice that returning a function was a simple matter of defining a new function inside the function, and returning it at the end - being careful to pass the appropriate parameters for each function. FYI, the technique of returning a function from another function is known as currying.