所以这段代码应该计算一个函数被调用的次数,但我试图通过运行下面的代码来更深入地理解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
) 返回的函数是每次调用装饰函数时执行的函数。