如何编写一个返回另一个函数的函数? [英] How do I write a function that returns another function?
问题描述
在 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?
推荐答案
试试这个,使用 Python:
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.
这篇关于如何编写一个返回另一个函数的函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!