【发布时间】: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