fork download
  1. # define a decorator method:
  2. def save_db_decorator(fn):
  3.  
  4. # The wrapper method which will get called instead of the decorated method:
  5. def wrapper(self, *args, **kwargs):
  6. fn(self, *args, **kwargs) # call the decorated method
  7. Test.save_to_db(self, *args, **kwargs) # call the additional method
  8.  
  9. return wrapper # return the wrapper method
  10.  
  11. class Test:
  12.  
  13. # The additional method called by the decorator:
  14.  
  15. def save_to_db(self, *args, **kwargs):
  16. print("Saver")
  17.  
  18.  
  19. # The decorated methods:
  20.  
  21. @save_db_decorator
  22. def crawl_1(self, *args, **kwargs):
  23. print("Crawler 1")
  24.  
  25. @save_db_decorator
  26. def crawl_2(self, *args, **kwargs):
  27. print("Crawler 2")
  28.  
  29.  
  30. # Calling the decorated methods:
  31.  
  32. test = Test()
  33. print("Starting Crawler 1")
  34. test.crawl_1()
  35. print("Starting Crawler 1")
  36. test.crawl_2()
  37.  
Success #stdin #stdout 0.02s 9984KB
stdin
Standard input is empty
stdout
Starting Crawler 1
Crawler 1
Saver
Starting Crawler 1
Crawler 2
Saver