string to object?
Guy Robinson
guy at NOSPAM.r-e-d.co.nz
Fri Jun 11 17:18:30 EDT 2004
Peter and Larry,
To clarify things more (as I should have done yesterday):
incompatible signatures are not what I want and I do understand I need
to instance the class first so yes
class foo:
def method1(self, *args):
return 'one'
def method2(self, *args):
return 'two'
ifoo=foo()
is more like it. I have a number of classes with methods. For various
reasons the class.method to run is only available as a string. The
arguments arrive independently. So the question is how can I convert a
string to a class.method object for instancing?
Pseudo python:
s = 'foo.method1'
arg = []
sclass,smethod = string2class(s)
isclass = sclass.smethod(arg)
TIA,
Guy
> 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