1.函数
import sysclass calcount01: def __init__(self, func): self.func = func self.call_num = 0 def __call__(self, *args, **kwargs): self.call_num += 1 print('self.call_num is: {} {}'.format(self.call_num, self.func.__name__)) #这是使用类装饰器的方法 return self.func(*args, **kwargs)@calcount01deff call_test(): print('----- in call_test, my func name: {}'.format(sys._getframe().f_code.co_name)) #这是第二个call_test()call_test()
2.计算函数运行时间和统计
# todo: record the real runtine by use this decoratorimport timeimport functoolsdef my_decorator(func): print('begin my_decorator') @functools.wraps(func) def my_wrapper(*args, **kwargs): print('begin my_wrapper') start_time = time.perf_counter() func(*args, **kwargs) end_time = time.perf_counter() print('function: {} , runtime: {} .'.format(func.__name__, (end_time - start_time))) return my_wrapper@my_decorator ### 在定义函数之前,用这个装饰器装饰,deff可以统计函数的运行时间 greet(name): print('hello from greet: {}'.format(name)) time.sleep(3)greet('xiaowei')print(greet.__name__)
用一个例子演示会更清晰