小编Fed*_*ega的帖子

了解这个 Python 装饰器的工作原理

我一直在研究如何创建自己的装饰器,并给出了以下示例:

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))
Run Code Online (Sandbox Code Playgroud)

我不明白那段代码的逻辑。

  1. 如何在自身内部引用函数 ( wrapper.count)?
  2. 在定义包装器之前包装器如何具有方法计数?
  3. 每次调用 foo() 时不应该执行行 wrapper.count = 0 吗?

wrapper python-3.x python-decorators

5
推荐指数
1
解决办法
144
查看次数

标签 统计

python-3.x ×1

python-decorators ×1

wrapper ×1