Invoking a method by name?

Brian Quinlan brian at sweetapp.com
Mon May 19 02:24:20 EDT 2003


> 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?
> 
> 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()

getattr(a, 'test')()
getattr(b, 'test')()

Cheers,
Brian






More information about the Python-list mailing list