1、带参数的装饰器
import time
flage=False
def time_out(flage):
def timer(fun):
def inner(*args,**kwargs):
if flage:
start=time.time()
ret=fun(*args,**kwargs)
end=time.time()
print(end-start)
return ret
else:
ret = fun(*args, **kwargs)
return ret
return inner
return timer
@time_out(flage)#等于执行time_out(flage)返回timer再执行@timer(@加timer)
def haha():
time.sleep(0.01)
print('哈哈哈')
@time_out(flage)#等于执行time_out(flage)返回timer再执行@timer(@加timer)
def nainiu():
time.sleep(0.01)
print('奶牛')
nainiu()
haha()
2、多个装饰器装饰一个函数
多个装饰器装饰一个函数执行顺序:先执行距离函数最近的装饰器
def wrapper1(func):
def inner1():
print('wrapper1 ,before func')
ret = func()
print('wrapper1 ,after func')
return ret
return inner1
def wrapper2(func):
def inner2():
print('wrapper2 ,before func')
ret = func()
print('wrapper2 ,after func')
return ret
return inner2
def wrapper3(func):
def inner3():
print('wrapper3 ,before func')
ret = func()
print('wrapper3 ,after func')
return ret
return inner3
@wrapper3#最后执行这个
@wrapper2#再执行这个
@wrapper1#先执行这个
def f():
print('in f')
return '哈哈哈'
print(f())
#记录用户的登录情况
#计算这个函数的执行时间
3、万能装饰器wraps
from functools
def wrapper(func): #func = holiday
@functools .wraps(func)#增加这个之后下面调用展示的holiday.__name__为holiday,否则为inner
def inner(*args,**kwargs):
print('在被装饰的函数执行之前做的事')
ret = func(*args,**kwargs)
print('在被装饰的函数执行之后做的事')
return ret
return inner
@wrapper #holiday = wrapper(holiday)
def holiday(day):
'''这是一个放假通知'''
print('全体放假%s天'%day)
return '好开心'
print(holiday.__name__)
ret = holiday(3) #inner
print(ret)
from functools
def wrapper(func): #func = holiday
@functools .wraps(func)#增加这个之后下面调用展示的holiday.__name__为holiday,否则为inner
def inner(*args,**kwargs):
print('在被装饰的函数执行之前做的事情')
ret = func(*args,**kwargs)
print('在被装饰的函数执行之后做的事情')
return ret
return inner
@wrapper #holiday = wrapper(holiday)
def holiday(day):
'''这是一个放假通知'''
print('全体放假%s天'%day)
return '好开心'
print(holiday.__name__)
ret = holiday(3) #inner
print(ret)
接受带参数和不带参数
import time,functools
def log(fs):
if isinstance(fs,str):#如果是字符串
def f(func):
@functools.wraps(func)
def fn(*args,**kwargs):
print('call %s'%func.__name__,fs)
result=func(*args,**kwargs)
return result
return fn
return f
else:
#否则 fs就是函数的指向
@functools.wraps(fs)
def fn(*args,**kwargs):
print('call %s'%fs.__name__)
result=fs(*args,**kwargs)
return result
return fn
@log('excute')
def s2():
print(time.strftime('%Y-%m-%d %H:%M:%d',time.localtime()))
return '我是s2函数'
@log
def s1():
print(time.strftime('%Y-%m-%d %H:%M:%d',time.localtime()))
return '我是s1函数'
print(s1())
print(s2())