且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

《Python数据科学指南》——1.14 返回一个函数

更新时间:2022-09-18 12:16:37

本节书摘来自异步社区《Python数据科学指南》一书中的第1章,第1.14节,作者[印度] Gopi Subramanian ,方延风 刘丹 译,更多章节内容可以访问云栖社区“异步社区”公众号查看。

1.14 返回一个函数

在这节里,我们讨论在一个函数里返回另一个函数。

1.14.1 准备工作

我们举一个高中的例子来说明咱们使用返回一个函数的函数。我们要解决的问题是:给定半径,求出不同高度的圆柱体的容积。

请参见:http://www.mathopenref.com/cylindervolume.html

Volume = area * height = pi * r^2 * h

上面的公式可以准确地求出圆柱体的体积。

1.14.2 操作方法

我们写一个简单的函数来演示在函数中返回函数的概念,此外还有一小段代码介绍如何使用。

# 1.定义一个函数来演示在函数中返回函数的概念
def cylinder_vol(r):
     pi = 3.141
     def get_vol(h):
          return pi * r**2 * h
     return get_vol

# 2.定义一个固定的半径值,在此给定半径和任意高度条件下,写一个函数来求出体积
radius = 10
find_volume = cylinder_vol(radius)

# 3.给出不同的高度,求解圆柱体的体积
height = 10
print "Volume of cylinder of radius %d and height %d = %.2f cubic\
units" %(radius,height,find_volume(height))
height = 20
print "Volume of cylinder of radius %d and height %d = %.2f cubic\
units" %(radius,height,find_volume(height))

1.14.3 工作原理

在第1步中,我们定义了函数cylinder_vol(),它只有一个参数r,即半径。在这个函数中,我们定义了另一个函数get_vol(),这个函数获取r和pi的值,并将高度作为参数。对于给定的半径r,也即cylinder_vol()的参数,不同高度值被作为参数传递给了get_vol()。

在第2步中,我们定义了半径,在本例中具体值为10,调用并传递给了cylinder_vol()函数,这个函数返回了get_vol()函数,我们把它存在名为find_volume的变量中。

在第3步中,我们使用不同的高度值来调用find_volume,如10和20,请注意我们没有给出半径值。

输出结果如下。

Volume of cylinder of radius 10 and height 10 = 3141.00 cubic units
Volume of cylinder of radius 10 and height 20 = 6282.00 cubic units

1.14.4 更多内容

Functools是高阶函数中的一个模块,请参考以下链接:

https://docs.python.org/2/library/functools.html