參考網(wǎng)址
> http://www.cnblogs.com/rhcad/archive/2011/12/21/2295507.html
> http://www.cnblogs.com/huxi/archive/2011/03/01/1967600.html
簡述
- 裝飾器的特點(diǎn)就是對已有的對象添加額外功能博烂,且不修改對象內(nèi)部代碼
- 使用裝飾器語法糖(@XXXXX)裝飾后,相當(dāng)于嵌套閉合函數(shù)語法糖指向的函數(shù)也就是一個高階函數(shù)漱竖,
被裝飾函數(shù)就是傳入的函數(shù)實(shí)參
一:不帶參數(shù)
#!/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的區(qū)別:
前者是一次性的禽篱,只對第一個func()有效,即28~19行代碼等效于func = time_calu1(func); func()
而后者可保證對每次調(diào)用的func()馍惹,都有效
二:帶參數(shù)
代碼:
#!/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