[英]How to evaluate the parameter of a function called from within decorator's wrapper?
[英]Understanding TypeError from decorator with function wrapper
Python裝飾器的新手,試圖理解以下代碼的“流程”:
def get_text(name):
return "lorem ipsum, {0} dolor sit amet".format(name)
def p_decorate(func):
print "here's what's passed to p_decorate(func): %s" % func
def func_wrapper(name):
print "here's what's passed to the inner func_wrapper(name) function: %s" % name
return "<p>{0}</p>".format(func(name))
return func_wrapper
my_get_text = p_decorate(get_text("fruit"))
print my_get_text("GOODBYE")
my_get_text = p_decorate(get_text)
print my_get_text("veggies")
為什么print my_get_text("GOODBYE")
行得到TypeError: 'str' object is not callable
?
如果我已經將該行中的get_text(name)
函數傳遞給了p_decorate(func)
,即使我也給了get_text()
一個字符串“ fruit”,為什么我不能用"GOODBYE"
重新分配name
參數傳遞的內容"GOODBYE"
?
您必須像這樣定義my_get_text
my_get_text = p_decorate(get_text)
因為p_decorate
需要一個函數作為參數,而get_text("fruit")
是一個字符串,因為這是get_text
在調用時返回的內容。 因此,錯誤。
這就是裝飾器要修改的功能。 如果將參數傳遞給函數,則會對其求值,並且結果(通常)與生成該參數的函數沒有任何關系。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.