有限状态机（Finite-state machine, FSM），又称有限状态自动机，简称状态机，是表示有限个状态以及在这些状态之间的转移和动作等行为的数学模型。FSM是一种算法思想，简单而言，有限状态机由一组状态、一个初始状态、输入和根据输入及现有状态转换为下一个状态的转换函数组成。现实世界中存在大量具有有限个状态的系统：钟表系统、电梯系统、交通信号灯系统、通信协议系统、正则表达式、硬件电路系统设计、软件工程，编译器等，有限状态机的概念就是来自于现实世界中的这些有限系统。

一个有限状态机包含如下几个要素：

- 状态：系统所处的状态，在运行过程中又可以分为当前状态和下一阶段状态；
- 事件：也可以理解为每一次运行的输入；
- 条件：根据输入事件执行的判定条件，条件是基于状态的，当前所处的每一种状态，都可以有自己对应的一套判定条件，来决定下一步进入哪一种状态；
- 动作：确定切换路径后，执行的附加操作。

以下是以OOP的方式，做了一个基础的Python实现。

FSM基类：
```python
class StateMachine:
    def __init__(self, cfg, states, events_handler, actions_handler):
        # config information for an instance
        self.cfg = cfg
        # define the states and the initial state
        self.states = [s.lower() for s in states]
        self.state = self.states[0]
        # process the inputs according to current state
        self.events = dict()
        # actions according to current transfer 
        self.actions = {state: dict() for state in self.states}
        # cached data for temporary use
        self.records = dict()
        # add events and actions
        for i, state in enumerate(self.states):
            self._add_event(state, events_handler[i])
            for j, n_state in enumerate(self.states):
                self._add_action(state, n_state, actions_handler[i][j])

    def _add_event(self, state, handler):
        self.events[state] = handler

    def _add_action(self, cur_state, next_state, handler):
        self.actions[cur_state][next_state] = handler

    def run(self, inputs):
        # decide the state-transfer according to the inputs
        new_state, outputs = self.events[self.state](inputs, self.states, self.records, self.cfg)
        # do the actions related with the transfer 
        self.actions[self.state][new_state](outputs, self.records, self.cfg)
        # do the state transfer
        self.state = new_state
        return new_state

    def reset(self):
        self.state = self.states[0]
        self.records = dict()
        return

# handlers for events and actions, event_X and action_XX are all specific functions
events_handlers = [event_A, event_B]
actions_handlers = [[action_AA, action_AB],
                    [action_BA, action_BB]]

# define an instance of StateMachine
state_machine = StateMachine(cfg, states, events_handlers, actions_handlers)
```

如果对于状态机有具体的要求，可以继承这个基类进行派生。

比如，有对状态机分层嵌套的需求。

```python
class StateGeneral(StateMachine):
    def __init__(self, cfg, states):
        super(StateGeneral, self).__init__(cfg, states, events_handler, actions_handler)
        self.sub_state_machines = dict()

    def add_sub_fsm(self, name, fsm):
        self.sub_state_machines[name] = fsm

    def run(self, inputs):
        new_state, outputs = self.events[self.state](inputs, self.states, self.records, self.cfg)
        # operate the sub_state_machines in actions
        self.actions[self.state][new_state](outputs, self.records, self.cfg, \
                 self.sub_state_machines)
        self.state = new_state
        return new_state

    def reset(self):
        self.state = self.states[0]
        self.records = dict()
        for _, sub_fsm in self.sub_state_machines.items():
            sub_fsm.reset()
        return
```
spam fails_task lang_mismatch pii not_appropriate hate_speech sexual_content quality toxicity humor helpfulness creativity violence