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

转载于:https://www.cnblogs.com/3one/p/5547761.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值