了解Python装饰器-这是示例中的变量吗?

时间:2019-04-30 19:35:27

标签: python decorator

我正在阅读以下有关Python装饰器tutorial的教程。除以下代码外,其他所有内容都差不多:

def call_counter(func):
    def helper(x):
        helper.calls += 1
        return func(x)
    helper.calls = 0

    return helper

@call_counter
def succ(x):
    return x + 1


print(succ.calls)
for i in range(10):
    succ(i)

print(succ.calls)

我无法完全理解helper.calls表示法。是仅与helper函数无关的变量吗?还有succ函数如何访问calls

2 个答案:

答案 0 :(得分:2)

我们可以将装饰重写为此:

def succ(x):
    return x + 1

succ = call_counter(succ)

所以现在您有了一个修饰过的succ。如您在call_counter中所见,它实际上返回了一个名为helper的函数。此helper函数具有一个名为calls的属性,该属性用于计数呼叫。因此,现在当您调用succ(i)时,实际上是在调用该helper函数。

是的,calls只是一个普通变量。

答案 1 :(得分:2)

在Python中,函数是对象,这意味着您也可以设置变量。

def func():
    pass

func.count = 0
print(func.count) # 0
func.count += 1
print(func.count) # 1