[英]How to put “if the function has been called this many times” in Python?
[英]How to test how many times a function has been called
假设我有一些代码可以像这样无限地运行一个函数:
def funct():
print "Hello"
while True:
funct()
有没有办法,我能考多少次的函数被调用( 不使用尝试 , 除了用递归误差 )的方式,然后执行一些更多的代码?
为您的函数定义一个函数属性,并在每次调用时对其进行修改。
def funct():
funct.callCount += 1
print "Hello"
funct.callCount = 0
更详细的方法是使用自定义装饰器来注册函数调用。
在下面的示例中,创建了一个Counter
类,其中包含一个类属性字典,该类字典包含有关每个函数调用频率的信息
class Counter(object):
counts = {}
@staticmethod
def count(func):
def wrapped(*args,**kwargs):
if func.__name__ in Counter.counts.keys():
Counter.counts[func.__name__] += 1
else:
Counter.counts[func.__name__] = 1
return func(*args,**kwargs)
return wrapped
@Counter.count
def test():
pass
@Counter.count
def test2():
test()
@Counter.count
def test3():
test()
test2()
for _ in range(4):
test3()
test2()
test()
print Counter.counts
这将输出:
{'test': 16, 'test3': 4, 'test2': 8}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.