【问题标题】:Counting the number of function calls计算函数调用的次数
【发布时间】:2018-12-29 04:24:04
【问题描述】:

所以,我有一个代码 sn-p 来计算函数调用的次数,在浏览潜在的最佳解决方案时,我遇到了几年前发布的类似问题:

is there a way to track the number of times a function is called?

上面线程中列出的解决方案之一与我的匹配,但存在细微差别。当我发布我的解决方案并询问我的代码中的潜在缺陷时,我的评论被删除了,即使我的评论是该问题的解决方案。所以,我希望这个不会因为重复而关闭,因为坦率地说,我不知道该去哪里。

这是我的解决方案:

def counter(func):
    counter.count=0
    def wrap(*args,**kwargs):
        counter.count += 1
        print "Number of times {} has been called so far 
            {}".format(func.__name__,counter.count)
        func(*args,**kwargs)
    return wrap

@counter
def temp(name):
    print "Calling {}".format(name)

我的计数器被定义为装饰器'counter'的属性,而不是包装函数'wrap'。该代码按当前定义工作。但是,是否存在可能失败的情况?我在这里忽略了什么吗?

【问题讨论】:

  • 当然。如果你装饰foo,调用它几百万次,然后定义一个名为bar的新函数并装饰它,那么你之前的foo计数就会消失。
  • 在 Python 装饰器库中有一个更好的 implementations,其中装饰器是一个类,可以使其实例(即它的使用)独立。
  • Martineau 的答案似乎是最好的答案。无论我在哪里定义计数器变量(在 'wrap' 内部或外部),它都不会计算跨多个函数的调用总数。当装饰器应用于新函数时,调用计数会重置。

标签: python python-2.7 python-decorators


【解决方案1】:

如果您在两个单独的函数上使用此装饰器,它们将共享相同的调用计数。那不是你想要的。此外,每次将此装饰器应用于新函数时,它都会重置共享调用计数。

除此之外,您还忘记在wrap 中传递func 的返回值,并且您不能在非三引号字符串中间添加未转义的换行符,例如那个。

【讨论】:

    【解决方案2】:

    对您的代码稍作修改,您就可以使您的 counter 装饰器独立:

    def counter(func, counter_dict={}):
        counter_dict[func]=0
        def wrap(*args,**kwargs):
            counter_dict[func] += 1
            print("Number of times {} has been called so far {}".format(func.__name__, counter_dict[func]))
            return func(*args,**kwargs)
        return wrap
    
    @counter
    def temp1(name):
        print("Calling temp1 {}".format(name))
    
    @counter
    def temp2(name):
        print("Calling temp2 {}".format(name))
    
    
    temp1('1')
    temp1('2')
    temp2('3')
    

    打印:

    Number of times temp1 has been called so far 1
    Calling temp1 1
    Number of times temp1 has been called so far 2
    Calling temp1 2
    Number of times temp2 has been called so far 1
    Calling temp2 3
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-11-19
      • 2021-06-10
      • 1970-01-01
      • 2023-01-11
      • 1970-01-01
      • 2020-02-13
      • 2021-01-09
      相关资源
      最近更新 更多