call function of class instance with no assigned name?

Arnaud Delobelle arnodel at googlemail.com
Tue May 5 18:17:10 CEST 2009


Chris Rebert <clp2 at rebertia.com> writes:

> On Tue, May 5, 2009 at 8:52 AM, George Oliver <georgeoliverGO at gmail.com> 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 could exploit Python's dynamism by using the getattr() function:
>
> key2cmd = {'h':'left'}
> cmd_name = key2cmd[keystroke]
> getattr("do_"+cmd_name, cmd_handler)() #same as cmd_handler.do_left()

getattr(cmd_handler, "do_" + cmd_name)() will work even better!

-- 
Arnaud



More information about the Python-list mailing list