装饰器的进阶
带参数的装饰器
import time FLAGE = False def timmer_out(flag): def timmer(func): 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 timmer @timmer_out(FLAGE) def funs(): time.sleep(0.2) print('大家好呀大家好') @timmer_out(FLAGE) def func(): time.sleep(0.2) print('新年好呀新年好') funs() func()
多个装饰器装饰一个函数
def wrapper1(func): def inner(*args,**kwargs): print('1111111') ret = func(*args,**kwargs) print('2222222') return ret return inner def wrapper2(func): def inner(*args,**kwargs): print('3333333') ret = func(*args,**kwargs) print('4444444') return ret return inner def wrapper3(func): def inner(*args,**kwargs): print('5555555') ret = func(*args,**kwargs) print('6666666') return ret return inner @wrapper3 @wrapper2 @wrapper1 def funs(): print('233') return '666' print(funs())