[Tutor] call a def/class by reference

Danny Yoo dyoo at hkn.eecs.berkeley.edu
Thu Sep 29 22:40:54 CEST 2005


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


Hi DS,


Modules can be thought of as containers for functions.  As a concrete
example, let's say we have a module named 'functions':

######
# in functions.py
def A(): print "A"

def B(): print "B"

def C(): print "C"
######


In other programs, this 'functions' module can be imported and dir()ed:

######
>>> import functions
>>> dir(functions)
['A', 'B', 'C', '__builtins__', '__doc__', '__file__', '__name__']
######


There are our attributes of the 'functions' module.  Those functions in
the module can also be called:

######
>>> getattr(functions, 'A')
<function A at 0x403a6ae4>
>>>
>>> getattr(functions, 'A')()
A
######


I'm not exactly sure if this is what you want, but this shows a simple way
to highlight a selection of functions, by using a module as the container.


Best of wishes!



More information about the Tutor mailing list