day20 Python 装饰器

时间:2023-03-09 22:19:04
day20 Python 装饰器

装饰器:本质就是函数,为其他函数添加附加功能,一个原则是不修改函数的源代码,另外一个原则是不修改被修饰函数的调用功能

装饰器=高阶函数+函数嵌套+闭包

前戏

import time
def cal(l):
start_time=time.time()
res=0
for i in l:
time.sleep(0.1)
res+=i
stop_time = time.time()
print('函数的运行时间是%s' %(stop_time-start_time))
return res print(cal(range(100))) def index():
pass def home():
pass

装饰器

import time

def timmer(func):
def warpper(*args,**kwargs):
start_time=time.time()
func()
stop_time=time.time()
print("the func run time is %s" % (stop_time-start_time))
return warpper @timmer
def test1():
time.sleep(3)
print("in the test1") test1() 结果:
in the test1
the func run time is 3.0026323795318604