Referencing objects own functions

Peter Otten __peter__ at web.de
Tue Oct 19 18:12:06 CEST 2004


pip 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.

As a rule of thumb, you can do everything in a class suite that can be done
in a function definition. 

def print_help(self):
   # code

binds the print_help name to a function object in the same way as
one = 1 binds 'one' to the integer object 1. Therefore you have to define it
before you can use the reference:

>>> class foo:
...     def print_help(self):
...             print "help is on the way"
...     commands = dict(
...             name="help",
...             desc="print help",
...             func=print_help)
...
>>> fooinst = foo()

There are two ways to call commands["func"], but both require that you
explicitly provide the self parameter:

>>> fooinst.commands["func"](fooinst)
help is on the way
>>> foo.commands["func"](fooinst)
help is on the way

While calling the function stored in the commands dictionary is a bit more
tedious than normal method invocation, all efforts to simply that depend
heavily on what you actually want to do with the function stored in the
dictionary.


Peter





More information about the Python-list mailing list