python - 了解 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
?
解决方案
我们可以将装饰重写为:
def succ(x):
return x + 1
succ = call_counter(succ)
所以现在你有一个装饰的succ
. 正如您在 中看到的call_counter
,它实际上返回了一个名为 的函数helper
。此helper
函数有一个名为的属性calls
,用于计算调用次数。所以现在当你打电话时succ(i)
,你实际上是在调用那个helper
函数。
是的,这calls
只是一个正常的变量。
推荐阅读
- adb - 授权弹出飞利浦 Android 电视不显示
- javascript - 在 Javascript 中访问数据数组时遇到问题
- python - 绘制定义大小的样本,直到列表为空。最后一次抽奖的大小
- c# - 我一直试图让单张卡出现在阵列之外,而其他卡则保持不活动状态
- python - Dataloader 对象不可下标的问题
- rust - 从 Rust 的 WebAssembly 中的 Window 对象获取查询字符串
- reactjs - 如何修复未捕获的错误:react-chartjs-2 中未实现此方法
- javascript - PhotoSphereViewer:javafx - JavaFX:尝试在标签中显示文本,在新窗口中,按下按钮后
- image-processing - 有没有一种无需机器学习就可以检测几何图案的智能方法?