无法理解python装饰器功能

时间:2020-05-19 19:42:59

标签: python function decorator

请注意,对于这个问题,我不知道该给什么。

我正在阅读有关创建装饰器的教程。疑问在第三行。我不完全了解。

我知道count不是函数。因为,我将wrapper.count更改为wrapper.cnt并且代码起作用了。但是,当我将wrapper.count更改为wrap.count时,就会出错。

这意味着我们正在从包装函数本身中引用包装函数。很好,但是关联的.count到底是什么?

请解释。下面是代码。

def counter(func):
  def wrapper(*args, **kwargs):
    wrapper.count += 1
    # Call the function being decorated and return the result
    func()
    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))

2 个答案:

答案 0 :(得分:1)

Python将函数视为对象,这意味着您可以为函数动态分配值。

Attribute.DateLastModified

因此,正在发生的事情是装饰器正在将变量def hello(): print(hello.some_variable) hello.some_variable = 'Hello!' hello() # Prints 'Hello!' hello.some_variable = 'Goodbye!' hello() # Prints 'Goodbye!' 分配给包装函数(在本例中为count)。然后,它从foo访问并递增该变量,然后进行打印。

答案 1 :(得分:0)

wrapper.count = 0

wrapper.countint。它以值0开头,每次您说wrapper.count += 1时都会递增。