装饰器在没有被称为

时间:2015-08-23 14:23:37

标签: python recursion decorator

我已经潜入Python装饰器并且正在玩一些方法来向装饰器添加函数参数。

我面临的问题与我想要在装饰器中进行递归同时仅在初始调用时设置一些变量。因此,在示例中,我想在函数调用上只打印一次消息。

现在它在函数定义上打印,而不是在函数调用上打印。请参阅此示例代码:

def recursiveCounter(message):
    def decorater(func):
        def wrapper(count):
            func(count)
            if count < 10:
                count += 1
                wrapper(count)

        print message
        return wrapper
    return decorater


@recursiveCounter("hello I was called once")
def counter(count):
    print count


counter(0)

1 个答案:

答案 0 :(得分:3)

下面我添加了注释,以指示每行的运行时间:

def recursiveCounter(message):  # when the decorator is defined
    def decorater(func):  # when the decorator is created - @recursiveCounter("hello I was called once")
        def wrapper(count):  # when the function is decorated - def counter(count): print count
            func(count)  # when the function is called - counter(0)
            if count < 10:  # when the function is called
                count += 1  # when the function is called 
                wrapper(count)  # when the function is called

        print message  # **when the function is decorated**
        return wrapper  # when the function is decorated
    return decorater  # when the decorator is created

如您所见,行print message在函数被装饰时运行,而不是在调用时运行。如果你希望它在调用函数时运行,你应该进一步缩进它,因此它在wrapper而不是decorater

如果您真的想保留递归实现,请重新排列包装器以定义并调用递归本身:

...
def wrapper(count):
    def inner_wrapper(count):
        if count < 10:
            inner_wrapper(count + 1)
    inner_wrapper(count)
    print message