将用户输入字符串转换为函数调用

Turn user input strings into a function call

我正在为基于文本的游戏编写词法分析器。我的代码如下所示的简化示例:

class Character:
    def goWest(self, location):
        self.location == location.getWest() #getWest() would be defined in the location class
x = raw_input("What action would you like to take")

使用此代码,我希望玩家输入如下内容:"Go West" 并使用单独的函数获取子字符串 "West",然后为该角色调用 goWest() 方法。

您应该使用多个 if 语句:

x = raw_input("What action would you like to take")
direction = x.split()[-1].lower()
if direction == "west":
    character.goWest(location)
elif direction == "east":
    character.goEast(location)
elif direction == "north":
    character.goNorth(location)
else:
    character.goSouth(location)

或者,您可以更改 go 函数:

class Character:
    def go(self, direction, location):
        self.location = location
        self.direction = direction
        #call code based on direction

然后将上面的内容作为:

x = raw_input("What action would you like to take")
character.go(x.split()[-1].lower(), location)

您可以使用 exec,但是 execeval 非常危险。

一旦你有了函数 goWest()goEast()goNorth()goSouth():

>>> func = "go"+x.split()[-1]+"()" #"goWest()"
>>> exec(func)
west