Skip to main content
 首页 » 编程设计

python之使用用户输入调用函数

2025年05月04日14sharpest

我试图在 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 

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

请您参考如下方法:

看起来您正在使用 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]()