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

时间:2015-04-26 18:28:54

标签: function python-2.7 user-input

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

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”,然后为该Character调用goWest()方法。

1 个答案:

答案 0 :(得分:1)

您应该使用多个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