一般来说,装饰器是一个函数,接受一个函数(或者类)作为参数,返回值也是也是一个函数(或者类)。首先来看一个简单的例子:
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)