python中的装饰器
1.写一个知道函数的执行时间的函数
import time
def tim():
start = time.time()
time.sleep(2)
print('该函数的执行时间是:')
end = time.time()
print(end - start)
tim()
2.如果我想对多个程序都要进行执行时间测量。都要写这样的程序岂不是很麻烦,所以把公共部分抽象出来
def func():
print('函数执行时间是')
def tim(f):
start = time.time()
time.sleep(2)
f()
end = time.time()
print(end - start)
tim(func)
3.有没有可以直接执行函数就实现了对函数的装饰呢?
def tim(f):
def inner():
start = time.time()
f()
end = time.time()
print(end - start)
return inner
def func():
print('执行该该函数')
func = tim(func)
func()
4.还有一种更加简便的方式实现装饰器函数
def tim(f):
def inner():
start = time.time()
f()
end = time.time()
print(end - start)
return inner
@tim
def func():
print('执行该该函数')
func()
5.带有返回值的装饰器
import time
def tim(f):
def inner():
start = time.time()
ret1 = f()
end = time.time()
print(ret1)
print(end - start)
return inner
@tim
def func():
time.sleep(2)
print('执行func函数')
return 'func函数的返回值'
func()
执行func函数
func函数的返回值
2.006819486618042
Process finished with exit code 0
6.func函数带参数的形式
import time
def tim(f):
def inner(a,b):
start = time.time()
ret1 = f(a,b)
end = time.time()
print(ret1)
print(end - start)
return inner
@tim
def func(a,b):
time.sleep(2)
print(a+b)
return 'func函数的返回值'
func(12,2)
7.万能参数和有返回值形式的装饰器
import time
def tim(f):
def inner(*args,**kwargs):
start = time.time()
ret = f(*args,**kwargs)
end = time.time()
print(ret)
print(end - start)
return inner
@tim
def func(*args,**kwargs):
time.sleep(2)
print('这里是func打印的内容')
print(*args,**kwargs)
return '这里是func函数返回的内容'
func('akjs',(1,5),2,{'s':2})
这里是func打印的内容
akjs (1, 5) 2 {'s': 2}
这里是func函数返回的内容
2.01223087310791
Process finished with exit code 0
总结装饰器的模板如下
装饰器的模板
def timmer(f):
def inner(*args,**kwarge):
'''被装饰函数执行之前要做的事'''
ret = f(*args,**kwarge)
'''被装饰函数执行之后要做的事'''
return ret
return inner
@timmer
def func(*args,**kwarge):
time.sleep(0.01)
print('老板哈',*args,**kwarge)
return 'haha'
func(实参)
|