Decorator运行时未被调用

2024-07-04 08:59:05 发布

您现在位置:Python中文网/ 问答频道 /正文

我深入研究了Python decorator,并尝试了一些向decorator添加函数参数的方法。在

我面临的问题是我想在decorator中执行递归,同时只在初始调用中设置一些变量。所以在这个例子中,我只想在函数调用中打印一次消息。在

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

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)

Tags: 方法messagereturndefcountcounterdecorator函数参数
1条回答
网友
1楼 · 发布于 2024-07-04 08:59:05

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

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而不是{}内。在


如果确实要保留递归实现,请重新安排包装器以定义和调用递归本身:

^{pr2}$

相关问题 更多 >

    热门问题