使用用户输入调用函数

Jon*_*Jon 2 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()
Run Code Online (Sandbox Code Playgroud)

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

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

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

mgi*_*son 6

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


一个更好的主意是将函数放入字典中——

def move():
    #...

def jump():
    #...

function_dict = {'move':move, 'jump':jump }
Run Code Online (Sandbox Code Playgroud)

进而:

func = input('>')  #raw_input on python2.x
function_dict[func]()
Run Code Online (Sandbox Code Playgroud)

以下代码在 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]()
Run Code Online (Sandbox Code Playgroud)