【发布时间】:2020-08-30 14:13:40
【问题描述】:
对于下面的功能,我正在努力理解
我。为什么wrapper.count = 0 在包装函数下面初始化?为什么不在 def counter(func) 下面初始化?为什么 wrapper.count 不将 wrapper.count 重置为 0,因为它在 wrapper 函数下方运行?
我想了解wrapper.count 是什么?为什么不初始化一个普通变量count 而不是wrapper.count?
def counter(func):
def wrapper(*args, **kwargs):
wrapper.count += 1
# Call the function being decorated and return the result
return func
wrapper.count = 0
# Return the new decorated function
return wrapper
# Decorate foo() with the counter() decorator
@counter
def foo():
print('calling foo()')
【问题讨论】:
-
" 为什么不在 def counter(func) 下面初始化" 因为
wrapper还没有定义。
标签: python function decorator wrapper