python 装饰器

python 装饰器Decorator

#在不改变函数代码的情况下,添加功能

import time

def timeDecorator(func):
def getTime(args):
t0 = time.time()
re = func(args)
print re
print "执行%s耗时%fs"%((func.func_name),(time.time() - t0))
#print func.func_name
return getTime
@timeDecorator
def getEven(args):
args = int(args)
i = 1
while i <= args:
print 2 * i
i += 1
return 'aaa'
getEven(100000)

执行结果:

2
4
6
......
200

aaa
执行getEven耗时0.001000s

 

#多参数装饰器(变量为函数)

def func2(a, b):
print 'func2'
def func3(c, d):
print 'func3'
def Decorator(before_func,after_func ):
def outer(main_func):
def wrapper(args, args2):
before_result = before_func(args, args2)
if before_result == None:
print 'before_func'
main = main_func(args, args2)
if main == None:
print 'main_func'
after_result = after_func(args, args2)
if after_result == None:
print 'after_func'
return wrapper

return outer


@Decorator(func2, func3)
def func1(args, args2):
print 'func1'
return 1
if __name__ == '__main__':
func1(0,0)

 

输出:

func2
before_func
func1
func3
after_func

posted @ 2016-05-31 22:08  3one  阅读(97)  评论(0编辑  收藏  举报