string to object?

Larry Bates lbates at swamisoft.com
Fri Jun 11 16:28:08 CEST 2004


This does what you asked for, but I suspect
it isn't the best way to accomplish what you
want to do (just guessing).  You can't call
a class, you must call an instance of a class
(e.g. ifoo below).

class foo:
    def method1(self, *args):
        return 'one'
    def method2(self, *args):
        return 'two'

ifoo=foo()
li=[ifoo.method1, ifoo.method2]

args=(1,)
for l in li:
    print apply(l, args)


HTH,
Larry Bates
Syscon, Inc.


"Guy Robinson" <guy at NOSPAM.r-e-d.co.nz> wrote in message
news:caccdm$fd$1 at lust.ihug.co.nz...
> Hello,
>
> I have a class:
>
> class foo:
>
> def method1(self,args):
> return 'one'
> def method2(self):
> return 'two'
>
> and I have a series of strings li = ['foo.method1','foo.method2']
>
> is there anyway I can do this?:
>
> for l in li:
> print l(args)
>
> getattr('foo','method1') didn't work as 'foo' is invalid.
>
> Any suggestions appreciated.
>
> Guy





More information about the Python-list mailing list