我剛剛開始使用Python,並且剛剛接觸到裝飾器。我寫了下面的代碼,模仿我所看到的,和它的作品:@decorators在Python中:爲什麼內部定義的函數?
def decorator_function(passed_function):
def inner_decorator():
print('this happens before')
passed_function()
print('this happens after')
return inner_decorator
@decorator_function
def what_we_call():
print('The actual function we called.')
what_we_call()
但後來我寫了這一點,這引發錯誤:
def decorator_function(passed_function):
print('this happens before')
passed_function()
print('this happens after')
@decorator_function
def what_we_call():
print('The actual function we called.')
what_we_call()
那麼,爲什麼我們需要有內裝飾器函數內部的嵌套函數?它的用途是什麼?僅僅使用第二種語法會不會更簡單?我沒有得到什麼?
有趣的是,這兩個具有相同的(正確)的輸出,但在第二個有錯誤文本爲好,說:「類型錯誤:‘NoneType’對象不是可調用的」
請用語言和例子適合對於剛開始使用Python的人來說,他的第一個編程語言 - 也是OOP的新手! :) 謝謝。
所以decorator_function僅僅是每當調用what_we_cal()時被調用的「引擎」,但inner_decorator是傳回的實際函數?所以我可以通過返回回傳任何東西,只要它是一個函數? – Sindyr
PS:如何格式化評論中的代碼塊? – Sindyr
所以你甚至可以寫這個: 'def decorator_function(passed_function): return other_function' 並且完全修正裝飾函數,是嗎? – Sindyr