简体   繁体   English

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

[英]How do I call functions from a dictionary in Python?

Easy one for you guys. 你们一个简单的。 Why can't I get cmd to run a function from a dictionary? 为什么我无法让cmd从字典运行函数? (I didn't want to paste all the code, but everything called has a class or function somewhere else. I have functions called "help()" and "exit() and such in a commands.py file and it's already been imported.) (我不想粘贴所有代码,但是所有被调用的东西在其他地方都有一个类或函数。我在commands.py文件中有一个名为“ help()”和“ exit()的函数,并且已经导入了。 )

The error I'm getting is: "line 87, in runCMD Commands[cmd](Player, args) KeyError: 0" 我得到的错误是:“ runCMD Commands [cmd](Player,args)KeyError:0中的第87行”

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)

You should be calling 你应该打电话

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

anyway, they first parameter of runCMD needs to be one of the keys in Commands 无论如何,它们的runCMD第一个参数必须是Commands中的键之一

Possibly you mean to pass an arbitrary number of parameters in args . 可能是您打算在args传递任意数量的参数。 then you need to place a * in there 那么您需要在其中放置一个*

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.")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM