装饰器的原理类似于以下函数
import time
def func():
time.sleep(0.1)
print('hello')
def timer(f):
def inner():
start=time.time()
f() #被装饰的函数
end=time.time()
print(end-start)
return inner
func=timer(func)# time(func)得到的是inner
func()
以下的代码就是装饰器
def timer(f):
def inner():
start=time.time()
f()
end=time.time()
print(end-start)
return inner
@timer #这里相当于func=time(func)
def func():
time.sleep(0.1)
print('hello')
func()
装饰器的作用:不想改变函数的调用方式 但是还是想在原来的函数上添加功能
来源:https://www.cnblogs.com/wind666/p/11963966.html