Invoking a method by name?
Alex Martelli
aleax at aleax.it
Mon May 19 02:31:17 EDT 2003
<posted & mailed>
Magnus Therning wrote:
> I need to call a method of an object where I only have the name of the
> method in a string. I have found one way, but I am not sure, maybe there
There's a simpler and faster one -- getattr(a, 'test')(). Offhand I do
not know what your approach does when 'test' doesn't name a method of a;
the getattr version raises AttributeError, but it's not too difficult to
tweak in order to make it raise something else or become an innocuous
no-op in that case (just pass as the third arg to getattr a suitable
callable to be used as 'default', e.g. via a lambda).
Alex
More information about the Python-list
mailing list