Invoking a method by name?

Magnus Therning magnus.therning at wanadoo.nl
Thu May 22 17:13:31 EDT 2003


Thanks, I expected there ought to be something like this. It works like
a charm!

/M

Brian Quinlan <brian at sweetapp.com> 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?
>> 
>> 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
> 
> 

-- 
Magnus Therning                    (OpenPGP: 0x6A83A7DF)

People who don't make mistakes make the greatest mistake of all;
they do nothing.
     -- Unknown




More information about the Python-list mailing list