二層裝飾器函數
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()函數的定義處,相當于執行了語句:
now = log(now)
三層裝飾器函數
由于log()是一個decorator,返回一個函數,所以,原來的now()函數仍然存在,只是現在同名的now變量指向了新的函數,于是調用now()將執行新函數,即在log()函數中返回的wrapper()函數。
wrapper()函數的參數定義是(*args, **kw),因此,wrapper()函數可以接受任意參數的調用。在wrapper()函數內,首先打印日志,再緊接著調用原始函數。
如果decorator本身需要傳入參數,那就需要編寫一個返回decorator的高階函數,寫出來會更復雜。比如,要自定義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)
我們來剖析上面的語句,首先執行log('execute'),返回的是decorator函數,再調用返回的函數,參數是now函數,返回值最終是wrapper函數。
以上兩種decorator的定義都沒有問題,但還差最后一步。因為我們講了函數也是對象,它有name等屬性,但你去看經過decorator裝飾之后的函數,它們的name已經從原來的'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()
那么我們怎樣才能給我們的裝飾器傳參數?要實現這個我們只需創建一個“decorator_factory”函數,我們調用這個函數,返回適用于我們函數的裝飾器。現在看看如果實現它。
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"