repsac

Difference between function and class decorators

May 28th, 2020
216
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.81 KB | None | 0 0
  1. # testing decorator functions
  2. def decorator1(func):
  3.  
  4.     def inner(value):
  5.         print(value)
  6.         inner.history = []
  7.         inner.history.append(value)
  8.    
  9.     return inner
  10.  
  11.  
  12. @decorator1
  13. def test1(value):
  14.     pass
  15.  
  16. print("Testing function decorators")
  17. test1(1)
  18. test1(2)
  19. print(test1.history)
  20.  
  21. # testing class functions
  22. class Decorator2(object):
  23.     def __init__(self, func):
  24.         self._func = func
  25.         self.history = []
  26.    
  27.     def __call__(self, value):
  28.         print(value)
  29.         self.history.append(value)
  30.  
  31.  
  32. @Decorator2
  33. def test2(value):
  34.     pass
  35.  
  36. @Decorator2
  37. def test3(value):
  38.     pass
  39.  
  40.  
  41. print("Testing class decorators")
  42. test2(1)
  43. test2(2)
  44. test3(3)
  45. print(test2.history)
  46.  
  47. """
  48. Testing function decorators
  49. 1
  50. 2
  51. [2]
  52. Testing class decorators
  53. 1
  54. 2
  55. 3
  56. [1, 2]
  57. """
Add Comment
Please, Sign In to add comment