繁体   English   中英

无法理解 python 装饰器 function

[英]Unable to understand the python decorator function

请注意,我不知道该回答这个问题的具体内容。

我正在学习创建装饰器的教程。 疑问在第三行。 我不完全理解。

我知道count不是 function。 因为,我将wrapper.count更改为wrapper.cnt并且代码有效。 但是当我将wrapper.count更改为wrap.count时,它会出错。

这意味着我们从包装器 function 本身中引用包装器 function。 很好,但是关联的.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))

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

def hello():
    print(hello.some_variable)

hello.some_variable = 'Hello!'
hello()  # Prints 'Hello!'

hello.some_variable = 'Goodbye!'
hello()  # Prints 'Goodbye!'

所以发生的事情是装饰器将变量count分配给包装的 function (在本例中为foo )。 然后它从foo访问并增加这个变量,然后你打印它。

wrapper.count = 0

wrapper.count是一个int 它从值 0 开始,每次你说wrapper.count += 1时递增。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM