string to object?
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
def method1(self, *args):
def method2(self, *args):
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?
s = 'foo.method1'
arg = 
sclass,smethod = string2class(s)
isclass = sclass.smethod(arg)
> 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'
> li=[ifoo.method1, ifoo.method2]
> for l in li:
> print apply(l, args)
> 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...
>>I have a class:
>>and I have a series of strings li = ['foo.method1','foo.method2']
>>is there anyway I can do this?:
>>for l in li:
>>getattr('foo','method1') didn't work as 'foo' is invalid.
>>Any suggestions appreciated.
More information about the Python-list