catalog.py 1.5 KB

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