# python裝飾器decorator
Python的 decorator 本質上就是一個高階函數,它接收一個函數作爲參數,然後,返回一個新函數。
使用 decorator 用Python提供的 @ 語法,這樣可以避免手動編寫 f = decorate(f) 這樣的代碼。
def log(f):
def fn(x):
print 'call ' + f.__name__ + '()...'
return f(x)
return fn
例子:
import time
def performance(f):
def fn(*args,**kargs):
start_time=time.time()
data=f(*args,**kargs)
stop_time=time.time()
dt=stop_time-start_time
print 'call'+f.__name__+ '() in %f seconds'%dt
return data
return fn
@performance
def factorial(n):
return reduce(lambda x,y: x*y, range(1, n+1))
print factorial(10)
輸出:callfactorial() in 0.209074 seconds
3628800
例子:要實現帶參數的@performance,就需要實現:
my_func = performance(‘ms’)(my_func)
需要3層嵌套的decorator來實現。
import time
def performance(unit):
def perf_decorator(f):
def wrapper(*args, **kw):
t1 = time.time()
r = f(*args, **kw)
t2 = time.time()
t = (t2 - t1) * 1000 if unit=='ms' else (t2 - t1)
print 'call %s() in %f %s' % (f.__name__, t, unit)
return r
return wrapper
return perf_decorator
@performance('ms')
def factorial(n):
return reduce(lambda x,y: x*y, range(1, n+1))
print factorial(10)
輸出:call factorial() in 6.862879 ms
3628800