Python 完成一组模拟后,将函数回调次数设置为1

Python 完成一组模拟后,将函数回调次数设置为1,python,counter,Python,Counter,您好,我有一个python包装函数,它计算函数被调用的次数,并根据每次调用次数执行一些操作,将内容写入html文件。现在有一种方法可以在一次迭代后将计数器设置回1,这样当我开始第二次迭代时,我希望htmloverview()的计数从开始开始,而不是从以前的值开始计数 Decorator: def counter(func): @wraps(func) def tmp(*args, **kwargs): tmp.count += 1

您好,我有一个python包装函数,它计算函数被调用的次数,并根据每次调用次数执行一些操作,将内容写入html文件。现在有一种方法可以在一次迭代后将计数器设置回1,这样当我开始第二次迭代时,我希望htmloverview()的计数从开始开始,而不是从以前的值开始计数

  Decorator:

   def counter(func):
      @wraps(func)
      def tmp(*args, **kwargs):
        tmp.count += 1
        return func(*args, **kwargs)
        tmp.count = 0
        return tmp

  @counter
  def htmloverview(fileouthtml,resultfile,file,identical,namesBothSub):
     r= htmloverview.count
     if(len(diff)==0):
        if(r==1):
          s = '\n'.join([message,message1,'<td>','0','</td>','</tr>'])
        else:
          s = '\n'.join(['<tr>','<td>',message1,'<td>','0','</td>','</tr>']) 
     fileouthtml.write(s)
     fileouthtml.write('\n') 
装饰器:
def计数器(func):
@包装(func)
def tmp(*args,**kwargs):
tmp.count+=1
返回函数(*args,**kwargs)
tmp.count=0
返回tmp
@柜台
def htmloverview(fileouthtml、resultfile、file、idential、namesBothSub):
r=htmloverview.count
如果(len(diff)==0):
如果(r==1):
s='\n'.加入([message,message1','0','','','','))
其他:
s='\n'.加入(['','',message1',,'0','','','','')
fileouthtml.write(s)
fileouthtml.write('\n')
我可以运行模拟器“n”次,每次运行时,我希望htmloverview的计数器从一开始就开始,而不是从上一次迭代开始计数,有没有办法做到这一点。

(如果可以,我会将此放在注释中)

我有点不确定你想要实现什么。在重置状态之前,是否希望函数在第一次调用时具有一种行为,在所有其他调用时具有另一种行为?然后,您可以将状态变量作为布尔参数传递:

def htmloverview(fileouthtml,resultfile,file,identical,namesBothSub, first_call) # True/False
或者可以将状态保存在全局变量中:

htmloverview_count=0

def htmloverview(fileouthtml,resultfile,file,identical,namesBothSub):

    global htmloverview_count

    if htmloverview_count>0:
        <do something>

     htmloverview_count+=1

如果您有许多具有类似行为的函数,那么使用decorator可能是有意义的。请详细说明您的问题:上述任何一项都能解决您的问题吗?

类似乎比装饰师更适合这里

class Simulation(object):
    def __init__(self, func):
        self.count = 0
        self._func = func
    def reset_count(self):
        self.count = 0
    def run(self, *args, **kwargs):
        self.count += 1
        return self._func(*args, **kwargs)

sim = Simulation(htmloverview)
for i in range(100): #first iteration
    sim.run(fileouthtml,resultfile,file,identical,namesBothSub)
print sim.count #ran 100 times
sim.reset()

您可以执行错误处理并保持错误计数,并且有多个模拟实例,每个实例都有自己的计数值

您可以对该问题提供更多描述吗?似乎您希望将变量
r
用作布尔值,而不是计数。或者您的问题是“htmloverview将在for循环中运行,然后需要重置计数器”?是的,htmloverview()将在for循环中运行,并且在循环完成后,需要重置计数器。
class Simulation(object):
    def __init__(self, func):
        self.count = 0
        self._func = func
    def reset_count(self):
        self.count = 0
    def run(self, *args, **kwargs):
        self.count += 1
        return self._func(*args, **kwargs)

sim = Simulation(htmloverview)
for i in range(100): #first iteration
    sim.run(fileouthtml,resultfile,file,identical,namesBothSub)
print sim.count #ran 100 times
sim.reset()