计算函数调用次数

时间:2018-07-20 20:03:18

标签: python python-2.7 python-decorators

因此,我有一个代码段来计算函数调用的数量,在浏览潜在的最佳解决方案时,我遇到了几年前在此处发布的类似问题:

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

上面的主题中列出的解决方案之一与我的匹配,但有细微的差别。当我发布解决方案并询问代码中的潜在陷阱时,即使我的问题得到了解决,我的评论也被删除了。因此,我希望不会关闭此副本,因为坦率地说,我不知道该去哪里。

这是我的解决方法:

paper-listbox

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

2 个答案:

答案 0 :(得分:3)

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

除此之外,您还忘记了通过func中的wrap的返回值,并且不能在非三元组中间插入未转义的换行符,用引号括起来的字符串文字。

答案 1 :(得分:1)

只需稍加修改即可使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