【问题标题】:Decorator is run without being called装饰器在没有被调用的情况下运行
【发布时间】:2015-11-17 00:19:36
【问题描述】:

我已经深入研究了 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)

【问题讨论】:

    标签: python recursion decorator


    【解决方案1】:

    下面我添加了 cmets 来指示每行运行的时间:

    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
    

    【讨论】:

    • 是的,但是当它在包装器中时,它将在递归中调用。这是我不想要的。
    • @JohnSmith 然后不要编写递归包装器!你不能同时拥有它。
    • @JohnSmith 或添加 inner_wrapper 以实现递归 - 请参阅编辑
    猜你喜欢
    • 2020-12-10
    • 1970-01-01
    • 2020-06-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-24
    • 2015-05-20
    相关资源
    最近更新 更多