简体   繁体   中英

Why doesn't this python decorator work?

I'm trying to understand decorators in python. I don't understand why the following doesn't work:

def decorator(func):
    def logger(*args, **kwargs):
        print "start logging"
        func(*args, **kwargs)
        print "end logging"
    return logger

@decorator
def add(a,b):
    return a+b

If I call add(2,3) the output will be:

start logging
end logging

However if I modify my code and write return func(*args, **kwargs) in the definition of logger it works but then end logging is not written on the output.

You can capture the return value in a variable, and return it after printing:

def decorator(func):
    def logger(*args, **kwargs):
        print "start logging"
        result = func(*args, **kwargs)
        print "end logging"
        return result
    return logger

Decorators are not special here; it's just a function calling another function.

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