Newbie: Changing a string to a class attribute.

David C. Fox davidcfox at post.harvard.edu
Wed Sep 24 22:35:45 CEST 2003


Jacob H wrote:

> This is a very simple problem and I'm sure the answer is a no brainer.
> However my brain can't see the answer. ;)
> 
> Given code like this:
> 
> def exec_method(object, method):
>     # object is an instantiated object, e.g. log
>     # method is a string that matches a method of object, e.g.
> "update"
>     # code stuff here that calls object.method, e.g. log.update()
>     
> What is the best way to turn method, a string, into a valid reference
> to the actual class method? My first thought was eval(). But I can't
> do this:
> 
>     eval("class.method()")
> 
> Eval will look for a method actually called method() and there isn't
> one. What's a good solution for this? Heck, for all I know, Python
> implicitly provides functionality to solve this problem. Can anyone
> help? :)

getattr(x, method)()

However, it isn't usually necessary to do this, because if x is an 
object with method update, x.update is an object which can be passed or 
stored.

David





> 
> Jake





More information about the Python-list mailing list