0
我正在通過實驗示例研究裝飾器和包裝器,我發現裝飾器的行爲,我不明白。python裝飾器和包裝函數調試
def decorator_function(original_function):
def wrapper_function():
print "wrapper is executed before {}".format(original_function.__name__)
return original_function() # Try it without()
return wrapper_function
@decorator_function
def display():
print("display function ran!")
當我運行上面的函數:
In [59]: display()
wrapper is executed before display
display function ran!
然而,當我移動打印功能的包裝之外,似乎包裝不會運行在所有。 (可能它跑了,但我沒有看到證據。)
def decorator_function(original_function):
def wrapper_function():
#print "wrapper is executed before {}".format(original_function.__name__)
return original_function() # Try it without()
print "wrapper is executed before {}".format(original_function.__name__)
return wrapper_function
@decorator_function
def display():
print("display function ran!")
然後我沒有看到「包裹被執行之前......」了。怎麼來的? 我在這裏錯過了什麼?
In [63]: display()
display function ran!
更確切地說,「包裝被執行」是在定義'display'時(這是'decorator_function'實際執行時)打印的。 – chepner