python怎么查看一次运行函数调用次数
时间: 2024-09-21 16:01:31 浏览: 37
python 限制函数调用次数的实例讲解
在Python中,如果你想查看一个函数被调用的次数,可以使用内置的`logging`模块或者第三方库如`wrapt`或`functools`。这里我会展示几种方法:
1. **使用`logging`**:
```python
import logging
def count_calls(func):
def wrapper(*args, **kwargs):
wrapper.calls += 1
return func(*args, **kwargs)
wrapper.calls = 0
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
logger.info(f"Logging decorator: {func.__name__}")
return wrapper
@count_calls
def my_function():
pass
# 调用函数
my_function()
```
每次调用`my_function`,你会看到一条日志记录显示调用次数。
2. **使用`functools`(装饰器)**:
```python
from functools import wraps
def call_counter(func):
@wraps(func)
def wrapper(*args, **kwargs):
wrapper.call_count += 1
return func(*args, **kwargs)
wrapper.call_count = 0
return wrapper
@call_counter
def my_function():
pass
print(my_function.call_count) # 调用后查看次数
```
3. **使用第三方库`wrapt`**:
```python
from wrapt import FunctionWrapper
class CallCounter(FunctionWrapper):
def __init__(self, wrapped, instance=None, args=(), kwargs={}):
super().__init__(wrapped, instance, args, kwargs)
self.call_count = 0
def __call__(self, *args, **kwargs):
self.call_count += 1
return self._original_function(*args, **kwargs)
my_function = CallCounter(my_function)
my_function() # 调用后查看wrapper.call_count
阅读全文