[Tutor] call a def/class by reference

bob bgailer at alum.rpi.edu
Thu Sep 29 20:20:07 CEST 2005


At 08:23 AM 9/29/2005, DS wrote:
>bob wrote:
>
> > At 04:29 PM 9/28/2005, DS wrote:
> >
> >> What I'm hoping to avoid is an
> >> explicit reference to any of the called functions within the program.
> >> By doing it that way, it would avoid a maintenance problem of having to
> >> remember to put a reference for every new function in the calling
> >> program.
> >
> >
> > Try this - a class in which you define all the functions. The __init__
> > method builds the dictionary.
> >
> > >>> class X:
> > ...     funcs = {}
> > ...     def y(self):
> > ...             pass
> > ...     def __init__(self):
> > ...             for itemname in dir(self):
> > ...                     if not itemname.startswith('__'):
> > ...                             item = getattr(self, itemname)
> > ...                             if callable(item):
> > ...                                     self.funcs[itemname] = item
> > ...
> > >>> y = X()
> > >>> y.funcs
> > {'y': <bound method x.y of <__main__.x instance at 0x01119828>>}
> >
>
>
>Thanks bob, that's an interesting approach.  That would be one huge class.

Well if you have lots of functions you will have one *huge* module. The 
additional class stuff is minor.

Also note that you can accomplish a similar thing by defining the functions 
outside any class and then finding them in globals(). Having said that I 
like the class approach in that it becomes a container for the functions 
you want to expose and other functions defined outside the class will be 
ignored. 



More information about the Tutor mailing list