call function of class instance with no assigned name?

Dave Angel davea at ieee.org
Tue May 5 14:59:21 EDT 2009


George Oliver wrote:
> hi, I'm a Python beginner with a basic question. I'm writing a game
> where I have keyboard input handling defined in one class, and command
> execution defined in another class. The keyboard handler class
> contains a dictionary that maps a key to a command string (like 'h':
> 'left') and the command handler class contains functions that do the
> commands (like def do_right(self):),
>
> I create instances of these classes in a list attached to a third,
> 'brain' class. What I'd like to have happen is when the player presses
> a key, the command string is passed to the command handler, which runs
> the function. However I can't figure out a good way to make this
> happen.
>
> I've tried a dictionary mapping command strings to functions in the
> command handler class, but those dictionary values are evaluated just
> once when the class is instantiated. I can create a dictionary in a
> separate function in the command handler (like a do_command function)
> but creating what could be a big dictionary for each input seems kind
> of silly (unless I'm misunderstanding something there).
>
> What would be a good way to make this happen, or is there a different
> kind of architecture I should be thinking of?
>
>   
You have lots of words, but no code, and no explanation of why you're 
choosing this "architecture."  So it's unclear just what to propose to 
you, without sticking to generalities.

1) forget about getattr() unless you have hundreds of methods in your 
map.  The real question is why you need two maps. What good is the 
"command string" doing you?   Why not just map the keyvalues directly 
into function objects?

2) Look at the following simple example, where I'm assuming that a 
"keycode" is simply an ASCII character.

class Command(object):
    def __init__(self):
        pass
    def doEnter(self):
        print "Enter is done"
    def doA(self):
        print "A is done"

cmd = Command()



table = {
    13: cmd.doEnter,
    65: cmd.doA
}

print "trying 13"
key = 13
table[key]()
print "trying 65"
key = 65
table[key]()

3) As for rebuilding the dictionary, that just depends on where you 
build it, and what it's lifetime is.  If it's got enough lifetime, and 
appropriate scope, you wouldn't have to rebuild anything.

4) Code up a first try, and when you get stuck, ask a specific question.

You said you're a beginner.  So keep it as simple as possible.l




More information about the Python-list mailing list