用wrapp函数理解decorator的TypeError

2024-05-29 03:33:35 发布

您现在位置:Python中文网/ 问答频道 /正文

对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参数的内容呢?你知道吗


Tags: textnameformatgetreturnheremydef
1条回答
网友
1楼 · 发布于 2024-05-29 03:33:35

你必须这样定义my_get_text

my_get_text = p_decorate(get_text)

因为p_decorate需要一个函数作为参数,get_text("fruit")是一个字符串,因为调用时get_text会返回这个字符串。因此出现了错误。你知道吗

这就是decorator所要做的,修改一个函数。如果将参数传递给函数,则会对其求值,结果(通常)与生成它的函数没有任何关联。你知道吗

相关问题 更多 >

    热门问题