二層裝飾器函數(shù)
def log(func):
def wrapper(*args, **kw):
print 'call %s():' % func.__name__
return func(*args, **kw)
return wrapper
@log
def now():
print '2013-12-25'
把@log放到now()函數(shù)的定義處,相當于執(zhí)行了語句:
now = log(now)
三層裝飾器函數(shù)
由于log()是一個decorator,返回一個函數(shù),所以,原來的now()函數(shù)仍然存在,只是現(xiàn)在同名的now變量指向了新的函數(shù),于是調(diào)用now()將執(zhí)行新函數(shù),即在log()函數(shù)中返回的wrapper()函數(shù)。
wrapper()函數(shù)的參數(shù)定義是(*args, **kw),因此,wrapper()函數(shù)可以接受任意參數(shù)的調(diào)用。在wrapper()函數(shù)內(nèi),首先打印日志,再緊接著調(diào)用原始函數(shù)。
如果decorator本身需要傳入?yún)?shù),那就需要編寫一個返回decorator的高階函數(shù),寫出來會更復(fù)雜。比如,要自定義log的文本:
def log(text):
def decorator(func):
def wrapper(*args, **kw):
print '%s %s():' % (text, func.__name__)
return func(*args, **kw)
return wrapper
return decorator
@log('execute')
def now():
print '2013-12-25'
和兩層嵌套的decorator相比,3層嵌套的效果是這樣的:
now = log('execute')(now)
我們來剖析上面的語句,首先執(zhí)行l(wèi)og('execute'),返回的是decorator函數(shù),再調(diào)用返回的函數(shù),參數(shù)是now函數(shù),返回值最終是wrapper函數(shù)。
以上兩種decorator的定義都沒有問題,但還差最后一步。因為我們講了函數(shù)也是對象,它有name等屬性,但你去看經(jīng)過decorator裝飾之后的函數(shù),它們的name已經(jīng)從原來的'now'變成了'wrapper':
# This is our decorator
def simple_decorator(f):
# This is the new function we're going to return
# This function will be used in place of our original definition
def wrapper():
print "Entering Function"
f()
print "Exited Function"
return wrapper
@simple_decorator
def hello():
print "Hello World"
hello()
那么我們怎樣才能給我們的裝飾器傳參數(shù)?要實現(xiàn)這個我們只需創(chuàng)建一個“decorator_factory”函數(shù),我們調(diào)用這個函數(shù),返回適用于我們函數(shù)的裝飾器。現(xiàn)在看看如果實現(xiàn)它。
def decorator_factory(enter_message, exit_message):
# We're going to return this decorator
def simple_decorator(f):
def wrapper():
print enter_message
f()
print exit_message
return wrapper
return simple_decorator
@decorator_factory("Start", "End")
def hello():
print "Hello World"