python以s记录函数调用次数
时间: 2023-10-19 12:20:21 浏览: 38
你可以使用装饰器来记录函数调用次数。下面是一个简单的例子:
```python
def count_calls(func):
"""装饰器函数,用于记录函数调用次数"""
def wrapper(*args, **kwargs):
wrapper.num_calls += 1
return func(*args, **kwargs)
wrapper.num_calls = 0
return wrapper
@count_calls
def my_func():
print("Hello World")
my_func()
my_func()
my_func()
print(f"my_func was called {my_func.num_calls} times")
```
输出结果:
```
Hello World
Hello World
Hello World
my_func was called 3 times
```
在这个例子中,`count_calls` 是装饰器函数,它接受一个函数作为参数,并返回一个新的函数 `wrapper`。`wrapper` 函数记录了被装饰函数 `func` 的调用次数,然后调用 `func`。在 `wrapper` 函数中,我们使用了一个变量 `num_calls`,它是一个属性。在 Python 中,函数也是对象,所以我们可以在函数对象上添加属性。最后,在 `my_func` 函数上使用装饰器 `@count_calls`,这样就可以记录 `my_func` 函数的调用次数。