1 # -*- coding: utf-8 -*- 2 def log_cost_time(func): 3 def wrapped(*args, **kwargs): 4 import time 5 begin = time.time() 6 try: 7 return func(*args, **kwargs) 8 finally: 9 print ‘func %s cost %s‘ % (func.__name__, time.time() - begin) 10 return wrapped 11 12 @log_cost_time 13 def complex_func(num): 14 ret = 0 15 for i in xrange(num): 16 ret += i * i 17 return ret 18 #complex_func = log_cost_time(complex_func) 19 20 if __name__ == ‘__main__‘: 21 print complex_func(100000)
@decdef func():pass
functools.
update_wrapper
(wrapper, wrapped[, assigned][, updated])This is a convenience function for invoking
partial(update_wrapper,wrapped=wrapped,assigned=assigned,updated=updated)
as a function decorator when defining a wrapper function.
1 import functools 2 def log_cost_time(func): 3 @functools.wraps(func) 4 def wrapped(*args, **kwargs): 5 import time 6 begin = time.time() 7 try: 8 return func(*args, **kwargs) 9 finally: 10 print ‘func %s cost %s‘ % (func.__name__, time.time() - begin) 11 return wrapped
1 def log_cost_time(stream): 2 def inner_dec(func): 3 def wrapped(*args, **kwargs): 4 import time 5 begin = time.time() 6 try: 7 return func(*args, **kwargs) 8 finally: 9 stream.write(‘func %s cost %s \n‘ % (func.__name__, time.time() - begin)) 10 return wrapped 11 return inner_dec 12 13 import sys 14 @log_cost_time(sys.stdout) 15 def complex_func(num): 16 ret = 0 17 for i in xrange(num): 18 ret += i * i 19 return ret 20 21 if __name__ == ‘__main__‘: 22 print complex_func(100000)
1 def Haha(clz): 2 clz.__str__ = lambda s: "Haha" 3 return clz 4 5 @Haha 6 class Widget(object): 7 ‘‘‘ class Widget ‘‘‘ 8 9 if __name__ == ‘__main__‘: 10 w = Widget() 11 print w
动态地为某个对象增加额外的责任
由于装饰器模式仅从外部改变组件,因此组件无需对它的装饰有任何了解;也就是说,这些装饰对该组件是透明的。
1 def catchall(func): 2 @functools.wraps(func) 3 def wrapped(*args, **kwargs): 4 try: 5 return func(*args, **kwargs) 6 except: 7 pass 8 return wrapped
原文:http://www.cnblogs.com/xybaby/p/6274187.html