python装饰器收录
计算函数调用次数
方法一 函数装饰器
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 @countclass 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)