[英]Understanding TypeError from decorator with function wrapper
New to Python decorators and trying to understand the "flow" of the following code: 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")
Why is it that the print my_get_text("GOODBYE")
line gets a TypeError: 'str' object is not callable
? 为什么print my_get_text("GOODBYE")
行得到TypeError: 'str' object is not callable
?
If I've already passed the get_text(name)
function to p_decorate(func)
in the line, even though I also gave get_text()
a string "fruit", why can't I reassign what's passed for the name
argument with "GOODBYE"
? 如果我已经将该行中的get_text(name)
函数传递给了p_decorate(func)
,即使我也给了get_text()
一个字符串“ fruit”,为什么我不能用"GOODBYE"
重新分配name
参数传递的内容"GOODBYE"
?
you have to define my_get_text
like this 您必须像这样定义my_get_text
my_get_text = p_decorate(get_text)
because p_decorate
needs a function as an argument and get_text("fruit")
is a string, since that is what get_text
returns when called. 因为p_decorate
需要一个函数作为参数,而get_text("fruit")
是一个字符串,因为这是get_text
在调用时返回的内容。 Hence the Error. 因此,错误。
That's what a decorator is about, modifying a function. 这就是装饰器要修改的功能。 If you pass an argument to a function it is evaluated and the result (usually) doesn't have any connection with the function that generated it. 如果将参数传递给函数,则会对其求值,并且结果(通常)与生成该参数的函数没有任何关系。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.