Newbie: Changing a string to a class attribute.
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.
> # 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:
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? :)
>>> class LOG:
... def up_date(self):
... print 'update'
>>> def exec_method(object, method):
... eval('object.'+method) ()
Hope that helps.
More information about the Python-list