2017-04-12 126 views
11
def makebold(fn): 
    def wrapped(): 
     return "<b>" + fn() + "</b>" 
    return wrapped 

def makeitalic(fn): 
    def wrapped(): 
     return "<i>" + fn() + "</i>" 
    return wrapped 

@makeitalic 
@makebold 
def hello(): 
    return "hello world" 

print(hello()) ## returns "<b><i>hello world</i></b>" 

在這段代碼中,爲什麼不直接定義函數makeitalic()和makebold()並傳入函數hello?Python裝飾器vs傳遞函數

我在這裏錯過了什麼,或者是裝飾者真的更適合更復雜的事情嗎?

回答

8

在這段代碼中,爲什麼不直接定義函數makeitalic()和makebold()並傳入函數hello?

你當然可以!裝飾者只是語法糖。引擎蓋下,會發生什麼情況是:

@makeitalic 
@makebold 
def hello(): 
    return "hello world" 

變爲:

def hello(): 
    return "hello world" 

hello = makebold(hello) 
hello = makeitalic(hello) 
+0

感謝,似乎沒有必要在這種情況下。我相信他們在其他使用案例中提供簡潔。 –