简体   繁体   中英

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? (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.)

The error I'm getting is: "line 87, in runCMD Commands[cmd](Player, 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)

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

Possibly you mean to pass an arbitrary number of parameters in 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.")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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