【发布时间】:2020-10-15 23:30:19
【问题描述】:
我一直在研究如何创建自己的装饰器,并给出了以下示例:
def counter(func):
def wrapper(*args, **kwargs):
wrapper.count += 1
# Call the function being decorated and return the result
return wrapper.count
wrapper.count = 0
# Return the new decorated function
return wrapper
# Decorate foo() with the counter() decorator
@counter
def foo():
print('calling foo()')
foo()
foo()
print('foo() was called {} times.'.format(foo.count))
我不明白那段代码的逻辑。
- 如何在自身内部引用函数 (
wrapper.count)? - 包装器在定义包装器之前如何计算方法计数?
- 每次调用 foo() 时不应该执行 line wrapper.count = 0 吗?
【问题讨论】:
-
响应第3点,包装函数仅在第一次修饰foo时调用,之后包装函数是包装foo的唯一函数,因此不会执行该行跨度>
标签: python-3.x wrapper python-decorators