Indirect Class Instance Invocation

Jiba a11w at SoftHome.net
Tue Nov 13 19:22:00 CET 2001


John Bell wrote:

> I feel that this should be do-able, but can't see how.  If I have some
> class foo and string s='foo', can I invoke bar as an instance of foo
> given only the string s?  (ie. bar=(something on s)() )A kind of setattr
> for classes rather than attributes.
> 
> John

There many solutions, depending where "foo" is defined...
E.g.

bar = globals()["foo"]()
bar = locals()["foo"]()
bar = getattr(module, "foo")()
# module is the module where foo is defined.

or even :
bar = eval("foo" + "()")

Jiba



More information about the Python-list mailing list