简体   繁体   中英

python decorator and wrapper function debug

I'm studying the decorator and the wrapper by experimenting examples and I found the behavior of decorator that I can't understand.

def decorator_function(original_function):
    def wrapper_function():
        print "wrapper is executed before {}".format(original_function.__name__)
        return original_function() # Try it without ()
    return wrapper_function

@decorator_function 
def display():
    print("display function ran!")

when I run above function:

In [59]: display()
wrapper is executed before display
display function ran!

However, when I move the print function outside of the wrapper, it seems the wrapper doesn't run at all. (Probably it ran but I don't see the evidence.)

def decorator_function(original_function):
    def wrapper_function():
        #print "wrapper is executed before {}".format(original_function.__name__)
        return original_function() # Try it without ()
    print "wrapper is executed before {}".format(original_function.__name__)    
    return wrapper_function

@decorator_function 
def display():
    print("display function ran!")

Then I don't see "wrapper is executed before..." anymore. How come? What am I missing here?

In [63]: display()
display function ran!

The decorator executes when your code loads , while the wrapper executes when your code runs . If I dump your second example into a file example.py and run it like this:

pythohn -i example.py

I see:

wrapper is executed before display
>>> 

That was the decorator running. Now if I call display() , I see the output from that function:

>>> display()
display function ran!
>>> 

I don't see the output from the decorator here because it already ran .

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