Guest User

Untitled

a guest
Jan 18th, 2019
95
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.51 KB | None | 0 0
  1. """
  2. We want to debug class methods, what we want is that whenever class method executes,
  3. it should print it’s fully qualified name before executing it’s body.
  4. """
  5.  
  6. from functools import wraps
  7.  
  8. def debug(func):
  9. '''decorator for debugging passed function'''
  10.  
  11. @wraps(func)
  12. def wrapper(*args, **kwargs):
  13. print("Full name of this method:", func.__qualname__)
  14. return func(*args, **kwargs)
  15. return wrapper
  16.  
  17. def debugmethods(cls):
  18. '''class decorator make use of debug decorator
  19. to debug class methods '''
  20.  
  21. # check in class dictionary for any callable(method)
  22. # if exist, replace it with debugged version
  23. for key, val in vars(cls).items():
  24. if callable(val):
  25. setattr(cls, key, debug(val))
  26. return cls
  27.  
  28. # sample class
  29. @debugmethods
  30. class Calc:
  31. def add(self, x, y):
  32. return x+y
  33. def mul(self, x, y):
  34. return x*y
  35. def div(self, x, y):
  36. return x/y
  37.  
  38. mycal = Calc()
  39. print(mycal.add(2, 3))
  40. print(mycal.mul(5, 2))
  41.  
  42. """
  43. if we want to apply this method decorator to all subclasses which inherit this Calc class.
  44. In that case we have to separately apply method decorator to every subclass just like we did with Calc class.
  45. so use meta class
  46.  
  47. from functools import wraps
  48.  
  49. def debug(func):
  50. '''decorator for debugging passed function'''
  51.  
  52. @wraps(func)
  53. def wrapper(*args, **kwargs):
  54. print("Full name of this method:", func.__qualname__)
  55. return func(*args, **kwargs)
  56. return wrapper
  57.  
  58. def debugmethods(cls):
  59. '''class decorator make use of debug decorator
  60. to debug class methods '''
  61.  
  62. for key, val in vars(cls).items():
  63. if callable(val):
  64. setattr(cls, key, debug(val))
  65. return cls
  66.  
  67. class debugMeta(type):
  68. '''meta class which feed created class object
  69. to debugmethod to get debug functionality
  70. enabled objects'''
  71.  
  72. def __new__(cls, clsname, bases, clsdict):
  73. obj = super().__new__(cls, clsname, bases, clsdict)
  74. obj = debugmethods(obj)
  75. return obj
  76.  
  77. # base class with metaclass 'debugMeta'
  78. # now all the subclass of this
  79. # will have debugging applied
  80. class Base(metaclass=debugMeta):pass
  81.  
  82. # inheriting Base
  83. class Calc(Base):
  84. def add(self, x, y):
  85. return x+y
  86.  
  87. # inheriting Calc
  88. class Calc_adv(Calc):
  89. def mul(self, x, y):
  90. return x*y
  91.  
  92. # Now Calc_adv object showing
  93. # debugging behaviour
  94. mycal = Calc_adv()
  95. print(mycal.mul(2, 3))
  96. """
Add Comment
Please, Sign In to add comment