计算python中函数的条目数

时间:2019-04-09 07:46:09

标签: python counter

我是python的新手。看起来似乎不太明显,但想知道python中是否有更简单的方法可以做到这一点。

我正在尝试对函数的数字条目进行计数。要求如下:

  • 每5秒钟触发一次计时器事件,通过该事件依次触发回调(ev_5ms())
  • 等待20秒,然后清除计数器,然后重新开始

我正在使用以下代码

counter = 0

"Callback"
def ev_5s():
if counter < 4:
    counter += 1
else
    counter = 0
    print('Send Message')

t = EventGenerator.TimerEventGenerator(1, ev_1s())
t.start()

错误回溯:

Traceback (most recent call last):
File "C:/Users/i8479/Desktop/Python/HPP_SM.py", line 28, in <module>
t = EventGenerator.TimerEventGenerator(1, ev_1s())
File "C:/Users/i8479/Desktop/Python/HPP_SM.py", line 21, in ev_1s
if counter < 4:
UnboundLocalError: local variable 'counter' referenced before assignment

我正在像在c或cpp中一样进行编码。如何在python中执行此操作?

3 个答案:

答案 0 :(得分:0)

一种解决方案是global

counter = 0

# Callback
def ev_5s():
    global counter
    if counter < 4:
        counter += 1
    else
        counter = 0
        print('Send Message')

t = EventGenerator.TimerEventGenerator(1, ev_1s())
t.start()

答案 1 :(得分:0)

这意味着您要将变量计数器传递给函数

更改行

def ev_5s(counter):

其他要更改的行

t = EventGenerator.TimerEventGenerator(1, ev_1s(counter))

答案 2 :(得分:0)

执行此操作的pythonic方式是拥有一个装饰器类,例如:

from functools import wraps
import time

class EventCounter(object):
  def __init__(self, reset_span):
    self.reset_span = reset_span
    self.running = False
    self.start_t = None
    self.counter = 0
  def __call__(self, f):
    @wraps(f)
    def wrapper(*args, **kwargs):
      if not self.running:
        self.start_t = time.time()
        self.counter += 1
        self.running = True
      elif (time.time() - self.start_t) > self.reset_span:
        self.start_t = time.time()
        self.counter = 0
      else:
        self.counter += 1
      print(f"Counter: {self.counter}")
      return f(*args, **kwargs)
    return wrapper


@EventCounter(2)
def foo():
  print("Foo")

运行:

for _ in range(5):
  foo()
  time.sleep(1)

结果:

Counter: 1
Foo
Counter: 2
Foo
Counter: 0
Foo
Counter: 1
Foo
Counter: 0
Foo

这里有live example