$ cat functs.py
def foo():
print "totot je foo"
def bar():
print "toto je bar"
def baz():
print "a nyni baz"
>>> import functs
>>> x = getattr( functs, 'bar' )
>>> x
<function bar at 0x2b0133cddcf8>
>>> x()
toto je bar
>>> x = getattr( functs, 'baz')
>>> x
<function baz at 0x2b0133cddd70>
>>> x()
a nyni baz
>>> x = getattr( functs, 'foo' )
>>> x
<function foo at 0x2b0133cddc80>
>>> x()
totot je foo
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
this is a nice way
func = getattr(obj, "method", None)
if callable(func):
func(args)
[ add comment ] ( 2 views ) | [ 0 trackbacks ] | permalink | related link