Invoking a method by name?
Andrew Bennetts
andrew-pythonlist at puzzling.org
Mon May 19 02:19:39 EDT 2003
On Mon, May 19, 2003 at 06:07:38AM +0000, 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
> is a more beautiful way to accomplish it?
There is.
> This is some example code:
>
> import inspect
>
> class test1:
> def test(self):
> print 'test'
>
> class test2(test1):
> def test(self):
> print 'extended test'
[..]
>
> a = test1()
> b = test2()
>
So far, so good. But rather than:
> inspect.getmembers(a, isrightfunc('test'))[0][1]()
> inspect.getmembers(b, isrightfunc('test'))[0][1]()
Use:
getattr(a, 'test')()
getattr(b, 'test')()
-Andrew.
More information about the Python-list
mailing list