在使用python实现时,有4种方式。大同小异。
catalog使用场景:
类初始化时,入参不同,那么后面执行相同的函数,执行体不同,输出不同。
其中一种写法:
class Catalog(object): """catalog of multiple static methods that are executed depending on an init parameter """ def __init__(self, param): # dictionary that will be used to determine which static method is # to be executed but that will be also used to store possible param # value self._static_method_choices = {'param_value_1': self._static_method_1, 'param_value_2': self._static_method_2} # simple test to validate param value if param in self._static_method_choices.keys(): self.param = param else: raise ValueError("Invalid Value for Param: {0}".format(param)) @staticmethod def _static_method_1(): print("executed method 1!") @staticmethod def _static_method_2(): print("executed method 2!") def main_method(self): """will execute either _static_method_1 or _static_method_2 depending on self.param value """ self._static_method_choices[self.param]()