python - 计算函数调用次数

标签 python python-2.7 python-decorators

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

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”。该代码按当前定义工作。但是,有没有可能会失败的情况呢?我在这里忽略了什么吗?

最佳答案

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

除此之外,您还忘记了在 wrap 中传递 func 的返回值,而且您不能在中间插入未转义的换行符像这样的非三引号字符串文字。

关于python - 计算函数调用次数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51449615/

相关文章:

python - python dict 的键默认排序发生了什么

python - 读取 excel 文件时将转换器应用于所有列,Python 3.6

python - 在循环中取消设置环境变量

python - 使用 Pub/Sub 和 Dataflow 从单个 JSON 创建多行并将其插入到 BigQuery

python - 有什么是 python 函数装饰器可以做而我不能用一流函数做的吗?

Python( Pandas ): replace value if previous value is same as next value

python - python中多个函数的异常处理

python - 子进程 check_output OSError : [Errno 2] No such file or directory

Python通过函数装饰器改造ast

具有函数属性的 Python 装饰器