Advertisement
lessientelrunya

Class Decorator

Apr 7th, 2017
77
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.85 KB | None | 0 0
  1. class count_calls(object):
  2.     counterdict = {}
  3.  
  4.     def __init__(self, fn):
  5.         self.fn = fn
  6.         self.func_name = self.fn.__name__
  7.         if not self.func_name in self.counterdict:
  8.             self.counterdict[self.func_name] = 0
  9.        
  10.     def __call__(self, *args, **kwargs):
  11.         self.counterdict[self.func_name] += 1
  12.         return self.fn(*args, **kwargs)
  13.    
  14.     def counter(self):
  15.         return self.counterdict[self.func_name]
  16.  
  17.     @classmethod
  18.     def counters(cls):
  19.         return cls.counterdict
  20.    
  21.     @classmethod
  22.     def reset_counters(cls):
  23.         cls.counterdict = {}
  24.  
  25. @count_calls
  26. def adding(*args):
  27.     return sum(args)
  28.  
  29. >>> adding(1, 2)
  30. 3
  31. >>> adding(3, 4)
  32. 7
  33. >>> adding(5, 6)
  34. 11
  35. >>> adding.counter()
  36. 3
  37. >>> adding.counters()
  38. {'adding': 3}
  39. >>> adding.reset_counters()
  40. >>> adding.counters()
  41. {}
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement