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

标签 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

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

最佳答案

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

关于python - 使用用户输入调用函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12495218/

相关文章:

asp.net - 使用 Python Mechanize 对 aspx 进行屏幕截图 - Javascript 表单提交

android - 如何在 Python 中实现 GCM HTTP 服务器同时避免我的服务器 IP 被谷歌列入黑名单?

python - pygame中的墙壁碰撞

python - 无法使正则表达式与 Python 一起使用

python - 我可以将 Django 的通用 View 与 google-app-engine-django 一起使用吗?

c++ - 如何将 Python 编译成 C++ .exe

python - Grep 查找包含 [] 的特定句子

python - 如何像在字典中一样根据 len-1 或 len+1 匹配单词? Python

python - 如何使用 python 数据修复翻转

python - 我怎样才能简化这个功能?