开发者

Problem with decorator

开发者 https://www.devze.com 2023-02-07 15:17 出处:网络
def my_decorator(func) : print \"I am a ordinary function\" def wrapper() : print \"I am function returned by the decorator\"
def my_decorator(func) :
    print "I am a ordinary function"
    def wrapper() :
        print "I am function returned by the decorator"
        func()
    return wrapper
def lazy_function() :
    print "zzzzzzzz"

functionDecora开发者_JAVA百科tor=my_decorator(lazy_function)

I have in Debug IO

I am a ordinary function

I don't get it why there is any output. I understand why this line:

functionDecorator()

returns me:

I am function returned by the decorator
another___zzzzzzzz

But for the rest I think I miss something


When you first call my_decorator, before it returns the the function wrapper, it will print your message.

Try calling functionDecorator() again, you won't get the output a second time because the function has already been decorated by my_decorator. Each time you call my_decorator, however, it will print your message, because it is a normal function call (that happens to also return a decorated function).

Also, see http://www.python.org/dev/peps/pep-0318/#current-syntax for alternative syntax for implementing decorators.


Decorator is a normal function, that takes another function and returns some modified function.

When you call:

functionDecorator=my_decorator(lazy_function)

code inside your decorator is instantly executed and so print statement is executed, new function is created and returned. Then, when you run decorated function (which is simply a new function built inside a decorator), only internal print is executed and the external is not executed ever again. Is that clear?

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号