how to access class methods via their name-as-string

Steven Bethard steven.bethard at gmail.com
Mon Jan 31 12:53:44 EST 2005


phil_nospam_schmidt at yahoo.com wrote:
> I'd like to be able to look up a method name by passing a string with
> the method name.

Use getattr:

py> class A(object):
...     def f(self):
...         pass
...     def g(self):
...         pass
...
py> class B(A):
...     def h(self):
...         pass
...
py> getattr(B(), 'f')
<bound method B.f of <__main__.B object at 0x011D7790>>
py> getattr(B(), 'g')
<bound method B.g of <__main__.B object at 0x01222390>>
py> getattr(B(), 'h')
<bound method B.h of <__main__.B object at 0x011D7790>>

Steve



More information about the Python-list mailing list