首页 > 解决方案 > 如何在 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()

谢谢。

标签: python-3.x

解决方案


推荐阅读