在P42-P45中我们提到,对于嵌套函数,可以在外部函数中直接调用内部函数;在P46闭包函数中我们知道可以将内部函数作为返回值;那么我们思考一下,是否可以将函数作为参数传递到另一个函数中呢?
def myfunc():
print('正在调用myfunc....')
def report(func):
print('主人,我要调用函数了....')
func()
print('主人,我调用完函数啦,快夸夸我')
report(myfunc)
我们设计一个时间管理大师程序,来计算传入函数的运行时间:
import time
def time_master(func):
print('Ready for run the procedure')
start = time.time() #获取初始时间戳
func()
stop = time.time() #获取结束时间戳
print('End the procedure')
print(f'The procedure expend {stop-start} 秒')
def myfunc():
time.sleep(2) #让程序等待2秒钟运行
print('Hello World')
time_master(myfunc)
如果我们想知道任何一个目标函数的运行时间,那么我们每次都需要显示的调用time_master函数。如何在调用目标函数时自动调用time_master函数呢?
import time
def time_master(func):
def call_func():
print('Ready for run the procedure')
start = time.time() #获取初始时间戳
func()
stop = time.time()
print('End the procedure')
print(f'The procedure expend {stop-start} 秒')
return call_func
def myfunc():
time.sleep(2)
print('Hello World')
myfunc = time_master(myfunc)
myfunc()
可看到,我们使用了 闭包函数 和 拿函数当参数 这俩个办法,实现了调用目标函数时自动调用time_master函数。我们将同时使用这俩个办法糅合成一个语法糖,将 myfun = time_master(myfunc) 写为 @time_master 放在 def myfun 上面,称为装饰器(Decorators)。上述代码段可写成:
import time
def time_master(func):
def call_func():
print('Ready for run the procedure')
start = time.time() #获取初始时间戳
func()
stop = time.time()
print('End the procedure')
print(f'The procedure expend {stop-start} 秒')
return call_func
@time_master
def myfunc():
time.sleep(2)
print('Hello World')
myfunc()