[Tutor] Calling a function by string name

Kent Johnson kent37 at tds.net
Fri Jul 21 19:27:12 CEST 2006


Smith, Jeff wrote:
> I have an object and I want to call a method that I have constructed 
> the name for in a string.
>  
> For example:
> str_method = 'myfun'
> obj.str_method
>  
> Of course, this fails.  I know I could probably do this with exec but 
> is there a better way?
Use getattr():

getattr(obj, 'myfun')()

Kent



More information about the Tutor mailing list