Obtaining an member function by name
Diez B. Roggisch
deets at nospam.web.de
Sat Nov 19 09:36:44 EST 2005
guy lateur wrote:
> Hi all,
>
> Suppose you have this class:
>
> class foo:
> def bar():
>
> Suppose you also have the strings "foo" and "bar". How can you obtain the
> function foo.bar()?
>
> Surely somebody knows..
getattr helps. However, your example won't work: it misses either a
staticmethod-declaration, or a self-argument, or a classmethod and
cls-argument. So unless we know if bar shall be an instance.method or
not, it's hard to tell what exactly you want. Because you could want
getattr(getattr(mymodule, "foo"), "bar")
Or
getattr(getattr(mymodule, "foo")(), "bar")
(notice the parentheses)
or
getattr(getattr(locals(), "foo"), "bar")
or
getattr(getattr(globals(), "foo"), "bar")
Diez
More information about the Python-list
mailing list