python之装饰器
Posted jak06
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python之装饰器相关的知识,希望对你有一定的参考价值。
转自: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
以上是关于python之装饰器的主要内容,如果未能解决你的问题,请参考以下文章