[Tutor] Help with classes

Kent Johnson kent37 at tds.net
Thu Apr 7 20:59:25 CEST 2005


Kevin wrote:
> I am fooling around with classes and I was trying to create a very
> small one player text adventure. I made a class called commands here
> it is:
> class Commands:
>     def __init__(self):
>         pass
>     def quiting(self):
>         sys.exit()
>     def look(self):
>         print "\nNot working yet!\n"
<snip more methods>

> while 1:
>     com = Commands()
>     a = ['look',
>          'get',
>          'take',
>          'kill',
>          'drink',
>          'eat',
>          'eq',
>          'help',
>          'quit']
>     commandl = raw_input(">>>: ")
>     if commandl not in a:
>         print "\nI don't understand that command?\n"
> 
> I want to beable to type in a command from the list at the prompt and
> have it call one of the functions from the class. I was looking for a
> shorter way to write it but the only way I can think of is with an if
> statment for each command. Is there a better way or shorter way to do
> this?

You can use introspection to do this:
cmd = getattr(com, commandl)
cmd()

In fact you could use introspection to replace the list a:
while 1:
   com = Commands()
   commandl = raw_input(">>>: ")
   if hasattr(com, commandl) and iscallable(getattr(com, commandl)):
     cmd = getattr(com, commandl)
     cmd()
   else:
     print "\nI don't understand that command?\n"

You can read a bit more about getattr() and hasattr() here:
http://docs.python.org/lib/built-in-funcs.html

Kent



More information about the Tutor mailing list