请注意,对于这个问题,我不知道该给什么。
我正在阅读有关创建装饰器的教程。疑问在第三行。我不完全了解。
我知道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))
答案 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.count
是int
。它以值0开头,每次您说wrapper.count += 1
时都会递增。