繁体   English   中英

使用函数包装器从装饰器了解TypeError

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM