装饰器进阶
装饰器的进阶
内容有三:
(1):functools.wraps
(2):带参数的装饰器
(3):多个装饰器装饰同一个函数
查看函数名和注释:
①查看函数名(字符串格式):函数名.____name____
②查看注释:函数名.____doc____
(1)functools.wraps
from functools import wraps def wrapper(func): @wraps(func) def inner(*args,**kwargs): print('在被装饰的函数执行之前要做的事') ret = func(*args,**kwargs) print('在被装饰的函数执行之后要做的事') return ret return inner @wrapper def holiday(day): ''' 注释 :param day: :return: ''' print('放假%s天'%day) return '好开心'
print('加functools.wraps之后:',holiday.__name__)#查看函数名字,此时为holiday本身
print(holiday.__doc__) #查看函数注释内容
ret = holiday(3)
print(ret)
三层装饰器:(即使有几百个被装饰的函数只需要修改FLAG就可以实现,使用或者不使用装饰器)(当FALG=False时不使用,反之则使用)
import time FLAGE = False def temmer_out(flag): def temmer(func): #func = qqxing def inner(*args,**kwargs): if flag: start = time.time() ret = func(*args,**kwargs) #被装饰的函数 end = time.time() print(end - start) return ret else: ret = func(*args, **kwargs) # 被装饰的函数 return ret return inner return temmer @temmer_out(FLAGE) #qqxing = temmer(qqxing) def qqxing(): time.sleep(0.1) print('QQ星星') return 1 print(qqxing())#inner
多个装饰器装饰同一个函数
def wrapper1(func): #func ----->f def inner1(): print('wrapper1,before func') func() #f print('wrapper1,after func') return inner1 def wrapper2(func): #func----->inner1 def inner2(): print('wrapper2,before func') func() #inner1 print('wrapper2,after func') return inner2 @wrapper2 # f =wrapper2(f)-----> wrapper2(inner1) = inner2 @wrapper1 # f = wrapper1(f) = inner1 def f(): print('in f') f()