1

我有一个装饰器,我想在函数通过装饰器路由时增加一个计数器。到目前为止,这是我的代码

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。如何汇总总次数?

4

2 回答 2

1

这应该这样做:

from functools import wraps
def count_check(function, count=[0]):
    """Returns number of times any function with this decorator is called
    """
    @wraps(function)
    def increase_count(*args, **kwargs):
        count[0] += 1
        return function(*args, **kwargs), count[0]

    return increase_count

您还可以花哨并使用字典来单独和单独计算函数:

from functools import wraps
def count_check(function, count={}):
    """Returns number of times any function with this decorator is called
    """
    count[function] = 0
    @wraps(function)
    def increase_count(*args, **kwargs):
        count[function] += 1
        return function(*args, **kwargs), count[function], sum(count.values())

    return increase_count

演示:

@count_check
def foo():
    return 42

print(foo(), foo(), foo())

@count_check
def bar():
    return 23

print(bar(), bar(), bar())
print(foo(), foo(), foo())

印刷:

(42, 1, 1) (42, 2, 2) (42, 3, 3)
(23, 1, 4) (23, 2, 5) (23, 3, 6)
(42, 4, 7) (42, 5, 8) (42, 6, 9)
于 2015-05-21T19:39:58.747 回答
0

我会尝试类似的东西:

from functools import wraps
count = 0
def count_check(function):
    @wraps(function)
    def increase_count(*args, **kwargs):
        global count
        count += 1
        return function(*args, **kwargs), count

    return increase_count
于 2015-05-21T19:40:57.840 回答