Referencing objects own functions

Alex Martelli aleaxit at yahoo.com
Tue Oct 19 17:51:03 EDT 2004


pip <jackson.pip at gmail.com> wrote:

> Hi all,
> 
> Pretend I have the following:
> 
> class foo:
>   commands = [
>     'name': 'help',
>     'desc': 'Print help',
>   ]
> 
>   def print_help(self):
>     print "Help is on the way!"
> 
> I would like to add another entry to the commands dict. called 'func'
> or something which contains a reference to a function in the foo
> class. What would the entry look like if atall possible?
> 
> I would rather not use eval if possible.

Wise (eval only in case of dire need:-).  I would use the name of the
method rather than the actual function object, for two reasons:
1. you can keep the commands dict BEFORE the def;
2. you can getattr and have the magic of descriptors work for you.

class foo:
     commands = dict(
         name='help',
         desc='Print help',
         func='print_help",
     )
 
     def print_help(self):
         print "Help is on the way!"

given an f=foo(), to call the 'func' you just need:

getattr(f, f.commands['func'])()

to get the same effect as f.print_help() would.  It doesn't get much
simpler, unless you instrument class foo (e.g. by inheriting from some
appropriate base class which wraps such operations into a nice readable
method).


Alex



More information about the Python-list mailing list