python调用序列中的decorator

2024-06-12 06:19:21 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试用python3编写一个decorator,它基本上保持对函数被调用次数的计数。 这是我的密码:

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

for i in range(10):
  print(succ(i))   # <--- ??

我理解decorator是如何工作的,但这里唯一让我困惑的是,第一次调用succ(x)得到了一个函数作为返回@call\u counter decorator。 然而,这里的主要困惑是我不太明白for循环中的顺序调用是如何在这里发生的?你知道吗

那么,在第一次调用返回一个函数(本例中是helper)之后,流是如何进行的呢。你知道吗

现在在for循环中,调用了such(0)、such(1)等等,这是如何工作的?我们是重用从第一次调用得到的返回函数,还是每次for循环被1添加时都调用decorator?你知道吗


Tags: 函数helperforreturndefcounterdecoratorcall
1条回答
网友
1楼 · 发布于 2024-06-12 06:19:21

decorator只在满足它时应用一次,然后所有succ的调用都使用返回的相同函数helper。你知道吗

如果只是在for循环中打印函数对象而不是调用它,则可以看到这一点:

for i in range(10):
  print(succ)
<function call_counter.<locals>.helper at 0x7fe4d05139d8>
<function call_counter.<locals>.helper at 0x7fe4d05139d8>
# ... so on, ten times.

流是直接向前的,helper每次都用传递给func的参数x调用。你知道吗

相关问题 更多 >