【问题标题】:Does a decorator run once even if the decorated function was called many times?即使装饰函数被多次调用,装饰器也会运行一次吗?
【发布时间】:2021-09-10 11:56:06
【问题描述】:

所以这段代码应该计算函数被调用的次数,但我试图通过在下面运行这段代码来更深入地理解python中的装饰,而不仅仅是复制代码

def counter(func):
    print('counter function executed')
    def wrapper(*args, **kwargs):
        print('wrapper function executed')
        wrapper.count += 1
        return func(*args, **kwargs)
    wrapper.count = 0
    return wrapper

@counter
def foo(i):
    return print(f'{i}')

foo('foo')
foo('foo')
foo('foo')
print(foo.count)

输出

counter function executed
wrapper function executed
foo
wrapper function executed
foo
wrapper function executed
foo
3

但装饰 foo() 应该等于 counter(foo)

为什么"counter function executed" 被打印一次??不是每次调用foo() 时都应该打印,这是否意味着装饰foo() 实际上等于wrapper(foo) .... 我说对了吗???

我得出这个结论是因为我认为wrapper.counter 将始终等于0,因为counter(foo) 会将wrapper.counter 的值重置为0

【问题讨论】:

  • 装饰调用装饰函数不同。装饰行为是一个函数调用,对被装饰函数的调用是另一个。修饰函数是wrapper,而不是counter

标签: python function python-decorators


【解决方案1】:

装饰器仅在定义装饰函数时运行,以便修改函数定义。装饰器返回的函数 (wrapper) 是每次调用装饰函数时执行的函数。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2010-11-08
    • 2019-11-07
    • 1970-01-01
    • 1970-01-01
    • 2020-04-28
    • 2019-02-22
    • 2010-09-25
    相关资源
    最近更新 更多