马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
我们知道,函数的参数是有作用域的,而且可以通过一些语句来改变作用域。函数装饰器的作用有点类似于改变函数作用域的语句。举个例子:
在下面的代码中,我们使用了装饰器@time_master从而改变了函数time_master, call_func, 和func的作用域,使其可以作用于函数myfunc。import time
def time_master(func):
def call_func():
print("Start to run program...")
start = time.time()
func()
stop = time.time()
print("End the program...")
print(f"The total time is {(stop-start):.2f} seconds.")
return call_func
@time_master
def myfunc():
time.sleep(2)
print("I love FishC.")
myfunc()
Start to run program...
I love FishC.
End the program...
The total time is 2.02 seconds.
如果我们把@time_master取消,那么我们得到的就只是函数mufunc的结果,示例如下:import time
def time_master(func):
def call_func():
print("Start to run program...")
start = time.time()
func()
stop = time.time()
print("End the program...")
print(f"The total time is {(stop-start):.2f} seconds.")
return call_func
def myfunc():
time.sleep(2)
print("I love FishC.")
myfunc()
I love FishC.
|