python中的有限状态机实现(switch case)

时间:2017-09-14 07:28:35

标签: python-2.7

当我在C中编码时,我使用大开关/外壳来实现我的FSM(有限状态机), 虽然python没有提供。有人建议使用字典或if / else子句,但这些解决方案似乎并不像switch / case子句那样有效。有没有其他方法在python中实现FSM?

1 个答案:

答案 0 :(得分:1)

python中切换案例的优雅解决方案是字典映射。 这是非常有效的,你可以看到它看起来干净:

def zero():
    return "0"

def one():
    return "1"

def two():
    return "2"

def num_to_func_to_str(argument):
    switcher = {
        0: zero,
        1: one,
        2: two,
    }

    # get the function based on argument
    func = switcher.get(argument)

    # Execute the function
    return func()

此模式允许您使用比switch语句更多的功能;因为您首先检索该函数,所以它允许您在执行之前检查/操作它。

另一种选择是实施切换器类。

class Switcher(object):
    def num_to_methods_to_str(self, argument):

        method_name = 'number_' + str(argument)
        method = getattr(self, method_name, lambda: "nothing")
        return method()

    def number_0(self):
        return "zero"

    def number_1(self):
        return "one"

    def number_2(self):
        return "two"