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

 

相关文章:

  • 2022-01-19
  • 2022-02-18
  • 2021-08-13
  • 2021-11-16
  • 2021-07-14
  • 2022-12-23
  • 2021-07-14
猜你喜欢
  • 2021-04-12
  • 2021-06-15
  • 2022-02-09
  • 2022-12-23
相关资源
相似解决方案