使用用户输入来调用函数

时间:2012-09-19 12:59:20

标签: python

我试图在Python中制作一个用户输入命令的“游戏”。但是,我不知道您是否可以将该输入作为函数名称。这是我目前的努力:

def move():
    print("Test.")

if __name__ == "__main__":
    input("Press enter to begin.")
    currentEnvironment = getNewEnvironment(environments)
    currentTimeOfDay = getTime(timeTicks, timeOfDay)
    print("You are standing in the {0}. It is {1}.".format(currentEnvironment, currentTimeOfDay))
    command = input("> ")
    command()

这里,输入是移动的,因为我想尝试调用该函数(作为潜在的最终用户可能)。但是,我收到以下错误:

Traceback (most recent call last):
  File "D:\Text Adventure.py", line 64, in <module>
    command()
TypeError: 'str' object is not callable

我想知道是否有任何方法可以让用户在游戏中“移动”,程序通过调用“移动”功能来实现。

4 个答案:

答案 0 :(得分:2)

查看cmd模块。见this

它通常用于shell风格的comman dlanguages,但它也可用于创建简单的文本风格冒险游戏。

您可以通过在Cmd子类上创建新方法来创建命令。

E.g。

def do_move(self, args):
    if self.next_room.has_snake():
        print "The next room contains a poisonous snake. It bites you and you die."
    else:
        print "The room is empty"

答案 1 :(得分:2)

看起来你正在使用python3.x,其中input返回一个字符串。要恢复python2.x行为,您需要eval(input())。但是,你不应该这样做。这可能会导致糟糕的一天。


更好的想法是将函数放入字典中 -

def move():
    #...

def jump():
    #...

function_dict = {'move':move, 'jump':jump }

然后:

func = input('>')  #raw_input on python2.x
function_dict[func]()

以下代码适用于python3.2。

def move():
    print("Test.")

func_dict = {'move':move}
if __name__ == "__main__":
    input("Press enter to begin.")
    currentEnvironment = "room" #getNewEnvironment(environments)
    currentTimeOfDay = "1 A.M." #getTime(timeTicks, timeOfDay)
    print("You are standing in the {0}. It is {1}.".format(currentEnvironment, currentTimeOfDay))
    command = input("> ")
    func_dict[command]()

答案 2 :(得分:2)

您可以使用以下方式按名称访问功能:

function = globals()[function_name]

如果该功能在当前模块中,或

function = getattr(other_module, function_name)

您还应该采取措施禁止调用任意函数,例如,前缀:

 def cmd_move() # ok to call this
 def cmd_jump() # ok to call this

 def internal_func....

 cmd = raw_input('>') # e.g. "move"
 fun = globals()['cmd_' + cmd]
 fun()

答案 3 :(得分:0)

汉斯建议重新使用代码通常会更好,但是如果你想输入命令并手动运行它们,那么拥有一个有效命令字典比直接执行用户提供的输入更安全。

cmd = { 'move': move, 'jump': jump, 'look': look }