[英]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.