catalog.py 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. """
  4. A class that uses different static function depending of a parameter passed in init
  5. Note the use of a single dictionnary instead of multiple conditions
  6. """
  7. __author__ = "Ibrahim Diop <http://ibrahim.zinaria.com>"
  8. __gist__ = "<https://gist.github.com/diopib/7679559>"
  9. class Catalog():
  10. """
  11. catalog of multiple static methods that are executed depending on an init parameter
  12. """
  13. def __init__(self, param):
  14. # dictionary that will be used to determine which static method is to be executed but
  15. # that will be also used to store possible param value
  16. self.static_method_choices = {'param_value_1': self.static_method_1, 'param_value_2': self.static_method_2}
  17. # simple test to validate param value
  18. if param in self.static_method_choices.keys():
  19. self.param = param
  20. else:
  21. raise Exception("Invalid Value for Param: {0}".format(param))
  22. @staticmethod
  23. def static_method_1():
  24. print("executed method 1!")
  25. @staticmethod
  26. def static_method_2():
  27. print("executed method 2!")
  28. def main_method(self):
  29. """
  30. will execute either static_method_1 or static_method_2
  31. depending on self.param value
  32. """
  33. self.static_method_choices[self.param]()
  34. def main():
  35. """
  36. >>> c = Catalog('param_value_1').main_method()
  37. executed method 1!
  38. >>> Catalog('param_value_2').main_method()
  39. executed method 2!
  40. """
  41. test = Catalog('param_value_2')
  42. test.main_method()
  43. if __name__ == "__main__":
  44. main()