【面试出题】基础-装饰器

实现一个装饰器,统计函数执行的时间和被调用的次数

 1 # !/usr/bin/env python
 2 # coding:utf-8
 3 import time
 4 from functools import wraps
 5 
 6 # 第一种 函数装饰器
 7 def timeCounter(func):
 8     num = 0
 9     @wraps(func)
10     def wrapper(*args, **kwargs):
11         nonlocal num
12         startTime = time.time()
13         func(*args, **kwargs)
14         num += 1
15         endTime = time.time()
16         return (num,round(endTime-startTime, 2))
17     return wrapper
18 
19 @timeCounter
20 def add(a, b):
21     time.sleep(2.115)
22     return a+b
23 
24 print(add(1,2))
25 print(add(1,3))
26 
27 # 第二种 类装饰器
28 class TimeCounter:
29     def __init__(self, func):
30         self.func = func
31         self.count = 0
32 
33     def __call__(self, *args, **kwargs):
34         start_time = time.time()
35         self.func(*args, **kwargs)
36         end_time = time.time()
37         self.count += 1
38         return (self.count, round(end_time - start_time, 2))
39 @TimeCounter
40 def add(a, b):
41     time.sleep(2.115)
42     return a+b
43 print(add(1, 3))

 

posted @ 2020-11-07 20:36  gtea  阅读(207)  评论(2编辑  收藏  举报