python-3.x - 如何在 python 中编写状态事件矩阵函数?
问题描述
我正在尝试在 python3.7 中编写一个状态事件矩阵,但我遇到了未定义错误的问题。
代码和我想问的都列在下面代码的注释中。
我宁愿按以下顺序编写代码 1) 状态定义 2) 事件定义 3) 状态事件矩阵 4) 单个函数 但是,当我在 python([2]) 中编写此代码时,我得到一个未定义的错误。
有没有办法在 [3] 中不使用 self 来编写这个?请帮我。
from enum import IntEnum, auto
class TestMatrix:
class State(IntEnum):
S00 = auto()
S01 = auto()
S02 = auto()
class Event(IntEnum):
E00 = auto()
E01 = auto()
E02 = auto()
# ([2] I would like to write the following position, but I get an undefined error.)
# func_list = (
# (f0000, f_nop, f_nop,),
# (f_nop, f0101, f_nop,),
# (f_nop, f_nop, f0202,),
# )
def __init__(self):
# ([3] I also understand that I can write the following using self)
# ( but I don't like the increase in width due to self...)
# self.func_list = (
# (self.f0000, self.f_nop, self.f_nop,),
# (self.f_nop, self.f0101, self.f_nop,),
# (self.f_nop, self.f_nop, self.f0202,),
# )
print('TestMatrix created.')
self.st = self.State.S00
def exec(self, ev):
st = self.st.value - 1
ev = ev - 1
self.func_list[st][ev](self)
# ([3] doesn't need self.)
# self.func_list[st][ev]()
def f_nop(self):
print('f_nop exec')
def f0000(self):
print('f0000 exec')
self.st = self.State.S01
def f0101(self):
print('f0101 exec')
self.st = self.State.S02
def f0202(self):
print('f0202 exec')
self.st = self.State.S00
# ([1] The followings gives me the expected behavior)
func_list = (
(f0000, f_nop, f_nop,),
(f_nop, f0101, f_nop,),
(f_nop, f_nop, f0202,),
)
def main():
mtx = TestMatrix()
mtx.exec(mtx.Event.E00.value)
mtx.exec(mtx.Event.E01.value)
mtx.exec(mtx.Event.E02.value)
# ([-] I would like to get the following output)
# TestMatrix created.
# f0000 exec
# f0101 exec
# f0202 exec
if __name__ == '__main__':
main()
谢谢。
解决方案
推荐阅读
- elasticsearch - 如何将 ElasticSearch 中的现有坐标转换为地理点
- wordpress - 如何使我的 wordpress 插件可翻译?
- python - 使用python从文件夹中的excel文件自动创建mysql表
- java - 如果 join 阻塞了主线程,为什么它不会阻塞在循环中?
- python - LSTM 时间序列异常检测
- reactjs - 将默认路由反转为私有路由,反之亦然
- java - 如何不仅从 google play 商店跟踪应用程序安装
- javascript - Javascript,如何使用正则表达式解析字符串
- java - 如何在 Java 中按照语言环境正确的顺序格式化日期和月份?
- php - 删除超过一小时的文档在弹性搜索中不起作用