參考博客鏈接
裝飾器可以對已經存在的函數(shù)進行封裝。
def get_text(name):
return "lorem ipsum, {0} dolor sit amet".format(name)
def p_decorate(func):
def func_wrapper(name):
return "<p>{0}</p>".format(func(name))
return func_wrapper
my_get_text = p_decorate(get_text)
print my_get_text("John")
# <p>Outputs lorem ipsum, John dolor sit amet</p>
在上面的方面中,我們并沒有改變get_text
本身的內容,只是在其
外部封裝了一個func_wrapper
函數(shù),同時在func_wrapper
外部添加一個裝飾器p_decorator
。
在裝飾器里面,有一個func_wrapper,我不是很清楚func_wrapper的機制,但是如果沒有func_wrapper的話,name參數(shù)就不能作為新的函數(shù)的輸入?yún)?shù)傳入。
函數(shù)有三種狀態(tài):1. 定義;2. 引用; 3. 調用
在上面的例子中:
my_get_text = p_decorate(get_text)
my_get_text = p_decorate(get_text("John"))
是調用加引用,先調用裝飾器,返回func_wrapper函數(shù),再用my_get_text方法引用func_wrapper。
而
my_get_text("John")
p_decorate(get_text())("John")
則是雙重調用,先調用裝飾器,然后再調用裝飾器返回來的函數(shù)。
整體就是p_decorate和func_wrapper兩者缺一不可,一個負責傳入待裝飾的函數(shù),一個是裝飾器返回的經過裝飾過的函數(shù)。
Python里面不需要顯式地進行賦值。用@符號即可。
def p_decorate(func):
def func_wrapper(name):
return "<p>{0}</p>".format(func(name))
return func_wrapper
@p_decorate
def get_text(name):
return "lorem ipsum, {0} dolor sit amet".format(name)
print get_text("John")
# Outputs <p>lorem ipsum, John dolor sit amet</p>