2017-04-10 115 views
1

我無法理解裝飾器的概念,所以基本上,如果我理解正確,裝飾器用於擴展函數的行爲,而無需修改函數代碼。基本例如:帶有參數的Python裝飾器

我有裝飾功能,這需要作爲參數,另一個函數,然後改變指定的參數函數的功能:

def decorator(f): 
    def wrapper(*args): 
    return "Hello " + str(f(*args)) 
return wrapper 

在這裏,我有我想裝飾功能:

@decorator 
def text (txt): 
'''function that returns the txt argument''' 
    return txt 

所以,如果我理解正確的話,實際發生的 「幕後黑手」 是:

d=decorator(text) 
d('some argument') 

我的問題是,在這種情況下會發生什麼,當我們在裝飾三個嵌套函數:

def my_function(argument): 
    def decorator(f): 
    def wrapper(*args): 
     return "Hello " +str(argument)+ str(f(*args)) 
    return wrapper 
return decorator 

@my_function("Name ") 
def text(txt): 
    return txt 

因爲功能是真棒,我可以在裝飾過的說法,我不明白到底發生了什麼背後這一呼籲:

@my_function("Name ") 

謝謝

+0

[python裝飾器與參數]的可能重複(http://stackoverflow.com/questions/5929107/python-decorators-with-parameters) – mkrieger1

回答

2

這是間接的只是一個水平,基本代碼等價於:

decorator = my_function("Name ") 
decorated = decorator(text) 
text = decorated 

沒有參數,你已經擁有的裝飾,所以

decorated = my_function(text) 
text = decorated 
0

my_function來這裏創建一個閉包。 argumentmy_function的本地。但由於關閉,當您返回decorator時,decorator函數始終有一個引用。因此,當您將decorator應用於text時,decorator會增加額外的功能,如預期的那樣。它還可以嵌入argument的額外功能,因爲它可以訪問定義它的環境。