gpt4 book ai didi

Python - 计算函数通过装饰器的次数

转载 作者:太空宇宙 更新时间:2023-11-03 17:42:05 24 4
gpt4 key购买 nike

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

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

它工作正常,直到另一个函数通过装饰器并且该函数的 count 重置为 0。如何汇总总次数?

最佳答案

这应该可以做到:

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)

关于Python - 计算函数通过装饰器的次数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30382556/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com