标签:star app over htm code imp 格式 wrapper flag
转自:http://www.cnblogs.com/Eva-J/articles/7194277.html
1、装饰器函数的固定格式
def wrapper(func): def inner(*args,**kwargs): ‘‘‘执行函数之前要做的‘‘‘ re = func(*args,**kwargs) ‘‘‘执行函数之后要做的‘‘‘ return re return inner
举例
import time def timer(func): def inner(*args,**kwargs): start = time.time() re = func(*args,**kwargs) print(time.time() - start) return re return inner @timer #==> func2 = timer(func2) def func2(a): print(‘in func2 and get a:%s‘%(a)) return ‘fun2 over‘ func2(‘aaaaaa‘) print(func2(‘aaaaaa‘))
2、带参数的装饰器函数
def outer(flag): def timer(func): def inner(*args,**kwargs): if flag: print(‘‘‘执行函数之前要做的‘‘‘) re = func(*args,**kwargs) if flag: print(‘‘‘执行函数之后要做的‘‘‘) return re return inner return timer @outer(False) def func(): print(111) func()
3、多个装饰器装饰同一个函数
def wrapper1(func): def inner(): print(‘wrapper1 ,before func‘) func() print(‘wrapper1 ,after func‘) return inner def wrapper2(func): def inner(): print(‘wrapper2 ,before func‘) func() print(‘wrapper2 ,after func‘) return inner @wrapper2 @wrapper1 def f(): print(‘in f‘) f()
显示如下:
wrapper2 ,before func wrapper1 ,before func in f wrapper1 ,after func wrapper2 ,after func
标签:star app over htm code imp 格式 wrapper flag
原文地址:https://www.cnblogs.com/zzq888/p/10303125.html