小编Fre*_*Bag的帖子

在python中为有限状态机分配函数作为变量

我正在尝试用 python 制作游戏,但遇到了根据游戏中的动作让对象切换状态的问题。

我发现最好的方法是使用某种方法将函数(对象的状态)定义为变量,并根据操作赋予对象一个状态。不幸的是,我不确定这是否可行,或者在谈到这个主题时可能有一个我还没有学习的概念。如果有人可以为我的问题提供解决方案,或者只是指出我学习解决问题的方法的方向。

有没有办法将某些函数/方法与名称相关联并避免多个if语句?

class stateUser:

    def __init__(self,state):
        self.state = state

    def executeState(self):
        if self.state == "Print Something":
            self.printSomething()
        elif self.state == "Not Print Something":
            self.dontPrint()
        else:
            self.notUnderstand()
        '''
            would like this function to simply call
            a function that is defined as the object's state,
            instead of using a bunch of if statements
        '''

    def printSomething(self):
        print("Something")

    def dontPrint(self):
        print("No")

    def notUnderstand(self):
        print("I didn't understand that")

runner = stateUser(None)
a = True
while a:
    runner.state = input("Enter …
Run Code Online (Sandbox Code Playgroud)

python oop python-3.x

3
推荐指数
1
解决办法
207
查看次数

标签 统计

oop ×1

python ×1

python-3.x ×1