[Tutor] getattr()

Kent Johnson kent37 at tds.net
Wed Jul 26 14:40:07 CEST 2006


János Juhász wrote:
>
> Dear All,
>
> I want to use getattr() to collect a list with all the functions on my 
> simple script those has got some functionname like 'On....'.
>
> #This should be the complete file
> def OnMenuFindMe():
>     print 'You found me'
>
> f = getattr(What_Should_It_Be???, 'OnMenuFindMe')
>
> f()
> #Till here
>
> It can use getattr() to get an object of a class or module, but not in 
> this much simpler situation. 
You can look up the function in the globals() dict, or you can import 
__main__, which is the top-level module, and use getattr() on it. Or you 
could wrap your functions in a class...

def OnMenuFindMe():
    print 'You found me'

f = globals()['OnMenuFindMe']

f()

import __main__

g = getattr(__main__, 'OnMenuFindMe')
g()

Kent



More information about the Tutor mailing list