[Tutor] call a def/class by reference
DS
ds-python-tutor at sidorof.com
Thu Sep 29 22:06:36 CEST 2005
bob wrote:
> 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.
>
I agree. My first thought when I saw that was that it would be a memory
issue, but then as I sat and thought about it, it I couldn't really tell
if it was any different than a huge module. One thing I don't have
experience with yet is the amount of memory taken when an instance of
the object is created. For example, does it use substantially more
memory if there are a bunch of if, elif clauses (representing the unused
functions within the class)? I'll monkey around with it and see what I get.
> 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.
>From what I've read so far, globals are actively discouraged. A class
seems like the best approach.
I'm actually pretty surprised that there isn't a built-in facility with
Python for referencing functions like this. In reading Python in a
Nutshell, prior to asking my questions here, I had thought that there
probably was, but I just wasn't grasping it.
Thanks.
ds
More information about the Tutor
mailing list