首页 > 解决方案 > 了解 Python 装饰器 - 这是示例中的变量吗?

问题描述

我正在阅读以下关于 Python 装饰器教程的教程。除了以下代码之外,一切都或多或少清楚:

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

标签: pythondecorator

解决方案


我们可以将装饰重写为:

def succ(x):
    return x + 1

succ = call_counter(succ)

所以现在你有一个装饰的succ. 正如您在 中看到的call_counter,它实际上返回了一个名为 的函数helper。此helper函数有一个名为的属性calls,用于计算调用次数。所以现在当你打电话时succ(i),你实际上是在调用那个helper函数。

是的,这calls只是一个正常的变量。


推荐阅读