- # 定义一个计算乘方的函数
- def pow(base, exponent) :
- result = 1
- for i in range(1, exponent + 1) :
- result *= base
- return result
- # 将pow函数赋值给my_fun,则my_fun可当成pow使用
- my_fun = pow
- print(my_fun(3 , 4)) # 输出81
- # 定义一个计算面积的函数
- def area(width, height) :
- return width * height
- # 将area函数赋值给my_fun,则my_fun可当成area使用
- my_fun = area
- print(my_fun(3, 4)) # 输出12
其实 python 已经内置了计算乘方的方法,因此此处的 pow() 函数并没有太大的实际意义,只是作为示范使用。
通过对 my_fun 变量赋值不同的函数,可以让 my_fun 在不同的时间指向不同的函数,从而让程序更加灵活。由此可见,使用函数变量的好处是让程序更加灵活。
- # 定义函数类型的形参,其中fn是一个函数
- def map(data, fn) :
- result = []
- # 遍历data列表中每个元素,并用fn函数对每个元素进行计算
- # 然后将计算结果作为新数组的元素
- for e in data :
- result.append(fn(e))
- return result
- # 定义一个计算平方的函数
- def square(n) :
- return n * n
- # 定义一个计算立方的函数
- def cube(n) :
- return n * n * n
- # 定义一个计算阶乘的函数
- def factorial(n) :
- result = 1
- for index in range(2, n + 1) :
- result *= index
- return result
- data = [3 , 4 , 9 , 5, 8]
- print("原数据: ", data)
- # 下面程序代码3次调用map()函数,每次调用时传入不同的函数
- print("计算数组元素的平方")
- print(map(data , square))
- print("计算数组元素的立方")
- print(map(data , cube))
- print("计算数组元素的阶乘")
- print(map(data , factorial))
Pthon 3 本身也提供了一个 map() 函数,Python 3 内置的 map() 函数的功能和此处定义的 map() 函数功能类似,但更加强大。
接下来的三行粗体字代码调用了 map() 函数三次,三次调用依次传入了 square、cube、factorial 函数作为参数,这样每次调用 map() 函数时实际的执行代码是有区别的。原数据: [3, 4, 9, 5, 8]
计算数组元素的平方
[9, 16, 81, 25, 64]
计算数组元素的立方
[27, 64, 729, 125, 512]
计算数组元素的阶乘
[6, 24, 362880, 120, 40320]
# 获取map的类型
print(type(map))
<class 'function'>
- def get_math_func(type) :
- # 定义一个计算平方的局部函数
- def square(n) : # ①
- return n * n
- # 定义一个计算立方的局部函数
- def cube(n) : # ②
- return n * n * n
- # 定义一个计算阶乘的局部函数
- def factorial(n) : # ③
- result = 1
- for index in range(2 , n + 1):
- result *= index
- return result
- # 返回局部函数
- if type == "square" :
- return square
- if type == "cube" :
- return cube
- else:
- return factorial
- # 调用get_math_func(),程序返回一个嵌套函数
- math_func = get_math_func("cube") # 得到cube函数
- print(math_func(5)) # 输出125
- math_func = get_math_func("square") # 得到square函数
- print(math_func(5)) # 输出25
- math_func = get_math_func("other") # 得到factorial函数
- print(math_func(5)) # 输出120
联系客服