Python 中的简单状态机

Simple State Machine in Python

我是 Python 的菜鸟,正在尝试构建状态机。我的想法是一本字典。所以当我输入一个键时,我得到一个值。然后我想切换一个功能。

def one():
    return "January"

def two():
    return "February"

def three():
    return "March"

def four():
    return "April"

def numbers_to_months(argument):
    switcher = {
        1: one,
        2: two,
        3: three,
        4: four,
    }

但我不知道该如何继续。我的目标是使用这些值来使用具有相同名称的函数。你们谁能帮我出出主意吗?

这不是真正的状态机,但您的意思可能是:

def numbers_to_months(argument):
    switcher = {
        1: one,
        2: two,
        3: three,
        4: four,
    }
    func_to_call = switcher[argument]
    func_to_call()

或者

def numbers_to_months(argument):
    switcher = {
        1: one,
        2: two,
        3: three,
        4: four,
    }
    func_to_call = switcher[argument]
    return func_to_call

您也可以使用 eval 调用 swicther 中的任何对象:

eval('switcher[1]()')                                                                                                                                                                             
# 'January'