[Tutor] call a def/class by reference

DS ds-python-tutor at sidorof.com
Thu Sep 29 23:14:29 CEST 2005


Danny Yoo wrote:

>>>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!
>
>  
>
Ok!!!   This is exactly it.  Thanks so much.  This provides the link
between a string that represents a function to the actual calling of
that function with getattr().  I was just reading up on the getattr()
because it was in used in Bob's answer, when your email came through.

Thanks so much to all of you that have answered my questions, including 
Liam.Clarke-Hutchinson, whom I didn't acknowledge directly with an
email.  I hope I'm not asking too many questions.  This is kind of a
departure for me.  Usually, I just bang my head against the wall till I
break through.  At some point I hope to get to a point where I can
provide answers for others who are just learning as well.

ds




More information about the Tutor mailing list