【发布时间】:2015-08-03 15:24:03
【问题描述】:
我有一个装饰器,我想在函数通过装饰器路由时增加一个计数器。到目前为止,这是我的代码
from functools import wraps
def count_check(function):
"""Returns number of times any function with this decorator is called
"""
count = []
@wraps(function)
def increase_count(*args, **kwargs):
count.append(1)
return function(*args, **kwargs), len(count)
return increase_count
它工作正常,直到另一个函数通过装饰器并将该函数的计数重置为 0。如何汇总总次数?
【问题讨论】:
-
为我工作。请显示实际产生不良行为的代码。
-
您好,没有错误,只是意外行为。例如,如果我用@count_check 装饰两个函数,它们都有自己的计数,而不是合计所有计数。
-
如果您想要对使用@count_check 修饰的函数的所有调用进行总计,则需要一个全局计数变量
标签: python decorator python-decorators functools