使用函数包装器从装饰器中理解 TypeError

Understanding TypeError from decorator with function wrapper

Python 装饰器的新手并试图理解以下代码的 "flow":

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 参数传递的内容?

你必须这样定义my_get_text

my_get_text = p_decorate(get_text)

因为 p_decorate 需要一个函数作为参数,而 get_text("fruit") 是一个字符串,因为调用时 get_text returns 就是这样。因此错误。

这就是装饰器的作用,修改函数。如果您将参数传递给一个函数,它会被计算并且结果(通常)与生成它的函数没有任何联系。