1.计算函数调用次数
# 方法一 函数装饰器
from functools import wraps
def countclass(func):
@wraps(func)
def wrapper(*args, **kwargs):
wrapper.count += 1
print(f'{func.__name__} has been called {wrapper.count} times')
rest = func(*args, **kwargs)
return rest
wrapper.count = 0
return wrapper
class CountCall:
def __init__(self, func):
self.count = 0
self.func = func
def __call__(self, *args, **kwargs):
self.count += 1
rest = self.func(*args, **kwargs)
print(f'{self.func.__name__} has been called {self.count} times')
return rest
@countcall
def add(a, b):
return a+b
@CountCall
def sum(a, b):
return a*b
add(4,5)
add(5,6)
add(6,7)
sum(1,2)
sum(2,3)
sum(3,4)
文章展示了两种方法来计算Python函数的调用次数:一是使用函数装饰器,二是定义一个包含__call__方法的类。通过@countcall装饰器和CountCall类,分别应用到add和sum函数上,每次调用这些函数时会打印出调用次数。
392

被折叠的 条评论
为什么被折叠?



