Guest User

Untitled

a guest
Oct 17th, 2017
46
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.00 KB | None | 0 0
  1. class MyClass:
  2.  
  3. def call(self, name):
  4. print "Executing function:", name
  5. getattr(self, name)()
  6.  
  7. def my_decorator(some_function):
  8. def wrapper():
  9. print("Before we call the function.")
  10. some_function()
  11. print("After we call the function.")
  12. return wrapper
  13.  
  14. @my_decorator
  15. def my_function(self):
  16. print "My function is called here."
  17.  
  18.  
  19. engine = MyClass()
  20. engine.call('my_function')
  21.  
  22. class MyClass:
  23.  
  24. def call(self, name):
  25. print "Executing function:", name
  26. getattr(self, name)()
  27.  
  28. def my_decorator(some_function):
  29. def wrapper():
  30. print("Before we call the function.")
  31. some_function()
  32. print("After we call the function.")
  33. return wrapper
  34.  
  35. # @my_decorator
  36. def my_function(self):
  37. print "My function is called here."
  38.  
  39.  
  40. engine = MyClass()
  41. engine.call('my_function')
  42.  
  43. >>> engine.my_function()
  44. Traceback (most recent call last):
  45. File "<stdin>", line 1, in <module>
  46. TypeError: 'NoneType' object is not callable
  47.  
  48. >>> MyClass.my_function is None
  49. True
  50.  
  51. def my_decorator(some_function):
  52. def wrapper(self):
  53. print("Before we call the function.")
  54. # some_function is no longer bound, so pass in `self` explicitly
  55. some_function(self)
  56. print("After we call the function.")
  57. # return the replacement function
  58. return wrapper
  59.  
  60. class MyClass:
  61.  
  62. def call(self, name, *args, **kwargs):
  63. print("Executing function: {!r}".format(name))
  64. getattr(self, name)(*args, **kwargs)
  65.  
  66. def my_decorator(some_function):
  67. def wrapper(self, *args, **kwargs):
  68. print("Before we call the function.")
  69. some_function(self, *args, **kwargs)
  70. print("After we call the function.")
  71.  
  72. return wrapper
  73.  
  74. @my_decorator
  75. def my_function(self):
  76. print("My function is called here.")
  77.  
  78. del my_decorator # Not a permanent part of class.
  79.  
  80.  
  81. engine = MyClass()
  82. engine.call('my_function')
Add Comment
Please, Sign In to add comment