使用用户输入来调用功能

发布于 2021-01-29 18:02:17

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

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

关注者
0
被浏览
88
1 个回答
  • 面试哥
    面试哥 2021-01-29
    为面试而生,有面试问题,就找面试哥。

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


推荐阅读
知识点
面圈网VIP题库

面圈网VIP题库全新上线,海量真题题库资源。 90大类考试,超10万份考试真题开放下载啦

去下载看看