Newbie: Changing a string to a class attribute.

Peter Abel PeterAbel at gmx.net
Thu Sep 25 22:27:24 CEST 2003


jacobsmail at gmx.net (Jacob H) wrote in message news:<33fbf9ec.0309241210.7acfddb9 at posting.google.com>...
> 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()")
> 

You're quite close!

> 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? :)
> 
> Jake

>>> class LOG:
... 	def up_date(self):
... 		print 'update'
... 
>>> log=LOG()
>>> 
>>> def exec_method(object, method):
... 	eval('object.'+method) ()
... 
>>> exec_method(log,'up_date')
update
>>> 
>>> 

Hope that helps.
Regards
Peter




More information about the Python-list mailing list