简体   繁体   中英

Understanding TypeError from decorator with function wrapper

New to Python decorators and trying to understand the "flow" of the following code:

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 ?

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" ?

you have to define my_get_text like this

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. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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