如何在Python中调用字典中的函数?

时间:2013-10-21 03:32:37

标签: python

对你们来说很容易。为什么我不能让cmd从字典中运行一个函数? (我不想粘贴所有代码,但所有调用的东西都有一个类或函数。我在commands.py文件中有一个名为“help()”和“exit()等函数,它已经被导入了。)

我得到的错误是:“第87行,在runCMD命令[cmd](播放器,args)中KeyError:0”

Commands = { #In-game commands
    'help': help,
    'stats': stats,
    'exit': exit
    }

def isValidCMD(cmd):
    if cmd in Commands:
        return True
    return False

def runCMD(cmd, Player, args):
    Commands[cmd](Player, args)

def main(Player): #Main function
    Player.dead = False
    while(Player.dead == False):
        cmd = input(">> ")

        if isValidCMD(cmd):
            runCMD(0, 1, Player)
        else:
            print("Please enter a valid command.")

charactercreation()
main(Player)

1 个答案:

答案 0 :(得分:1)

你应该打电话

runCMD(cmd, 1, Player) # or runCMD(cmd, Player, 1) <= looks like they are in the wrong order

无论如何,runCMD的第一个参数需要是Commands

中的一个键

可能你的意思是在args中传递任意数量的参数。然后你需要在那里放置一个*

def runCMD(cmd, Player, *args):
    Commands[cmd](Player, *args)

def main(Player): #Main function
    Player.dead = False
    while(Player.dead == False):
        cmd = input(">> ")

        if isValidCMD(cmd):
            runCMD(cmd, Player, 0, 1)
        else:
            print("Please enter a valid command.")