同样的代码实现对比,右图为使用装饰器之后的结果:
图1 | 图2 |
---|---|
myfunc=deco(myfunc) 其中deco(myfunc)返回wrapper,需要myfunc()进入wrapper()函数体内。 | @deco写在myfunc()前面,则可完成左图的功能;所以@装饰器的本质就是myfunc = deco(myfunc) |
源代码和运行结果如下:
import time
def deco(func):
def wrapper():
startTime = time.time()
func()
endTime = time.time()
msecs = (endTime - startTime) * 1000
print("->elapsed time: %f ms" %msecs)
return wrapper
@deco
def myfunc():
print("start myfunc")
time.sleep(0.6)
print("end myfunc")
print("myfunc is:" , myfunc.__name__)
myfunc()
myfunc is: wrapper
start myfunc
end myfunc
->elapsed time: 7506.299734 ms