string to object?
__peter__ at web.de
Fri Jun 11 10:01:11 EDT 2004
Guy Robinson wrote:
> I have a class:
> class foo:
> def method1(self,args):
> return 'one'
> def method2(self):
> return 'two'
Do you really want to allow incompatible signatures for the methods?
> and I have a series of strings li = ['foo.method1','foo.method2']
Does the part before the dot a class or an instance?
Does that instance/class vary over the list items?
> is there anyway I can do this?:
> for l in li:
> print l(args)
> getattr('foo','method1') didn't work as 'foo' is invalid.
That is because "foo" is a string, and strings don't have a method1()
> Any suggestions appreciated.
>>> class Foo:
... def method1(self, args):
... return "one"
... def method2(self, args):
... return "too"
>>> foo = Foo()
>>> args = (99,)
>>> calls = ["foo.method1", "foo.method2", "bar.method1"]
>>> bar = Foo()
>>> for instmethod in calls:
... inst, method = instmethod.split(".")
... print getattr(globals()[inst], method)(*args)
As you can see, various complications are possible. They might be avoided,
though, if you can describe your needs in plain English rather than with
the Python example, which happens to show too many loose ends.
More information about the Python-list