Python之装饰器

930 查看

参考网址
  > http://www.cnblogs.com/rhcad/archive/2011/12/21/2295507.html
  > http://www.cnblogs.com/huxi/archive/2011/03/01/1967600.html

简述

- 装饰器的特点就是对已有的对象添加额外功能,且不修改对象内部代码
- 使用装饰器语法糖(@XXXXX)装饰后,相当于嵌套闭合函数语法糖指向的函数也就是一个高阶函数,
   被装饰函数就是传入的函数实参

一:不带参数

  #!/usr/bin/python
  # -*- coding:utf-8 -*-

# 16 Oct. 2015
# Author:  Huang Junkai

import time

def time_calu1(func):
 def _extra():
     start = time.clock()
     func()
     end = time.clock()
     print 'total time:', end - start
 return _extra

 def time_calu2(func):
 start = time.clock()
 func()
 end = time.clock()
 print 'total time:', end - start
 return func

 @time_calu2
 def func():
 print 'Wow! Success'

 func()
 func()
看看两个装饰器time_calu1与time_calu2的区别:
前者是一次性的,只对第一个func()有效,即28~19行代码等效于func = time_calu1(func); func() 
而后者可保证对每次调用的func(),都有效

二:带参数

代码:

 #!/usr/bin/python
 -*- coding:utf-8 -*-

 # 16 Oct. 2015
 # Author:  Huang Junkai

 import time

 def time_calu1(func):
     def _extra(a, b):
         start = time.clock()
     result = func(a, b)
     end = time.clock()
     print 'used:', end - start
     return result
 return _extra


 def time_calu2(func):
 start = time.clock()
 func()
 end = time.clock()
 print 'used:', end - start
 return func


 @time_calu1
 def foo(a, b):
 # print 'Wow! Success: the result is %s' % (a + b)
 return a + b

 result = foo(1, 2)
 print result