catalog.py 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. """
  4. A class that uses different static function depending of a parameter passed in
  5. init. Note the use of a single dictionary 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
  12. parameter
  13. """
  14. def __init__(self, param):
  15. # dictionary that will be used to determine which static method is
  16. # to be executed but that will be also used to store possible param
  17. # value
  18. self._static_method_choices = {'param_value_1': self._static_method_1,
  19. 'param_value_2': self._static_method_2}
  20. # simple test to validate param value
  21. if param in self._static_method_choices.keys():
  22. self.param = param
  23. else:
  24. raise ValueError("Invalid Value for Param: {0}".format(param))
  25. @staticmethod
  26. def _static_method_1():
  27. print("executed method 1!")
  28. @staticmethod
  29. def _static_method_2():
  30. print("executed method 2!")
  31. def main_method(self):
  32. """
  33. will execute either _static_method_1 or _static_method_2
  34. depending on self.param value
  35. """
  36. self._static_method_choices[self.param]()
  37. def main():
  38. """
  39. >>> c = Catalog('param_value_1').main_method()
  40. executed method 1!
  41. >>> Catalog('param_value_2').main_method()
  42. executed method 2!
  43. """
  44. test = Catalog('param_value_2')
  45. test.main_method()
  46. if __name__ == "__main__":
  47. main()
  48. ### OUTPUT ###
  49. # executed method 2!