How to instatiate a class of which the name is only known at runtime?
__peter__ at web.de
Wed Sep 10 09:49:00 CEST 2003
Marco Herrn wrote:
> 1. How to do the import? I didn't find a way to give a string to the
> import statement.
> 2. How to write such code to instantiate?
Off topic: This thread like some others is spread over a few toplevel
entries in my newsreader (KNode 0.7.2). Is this a bug?
Anyway, putting it all together:
def getClass(classname, modulename):
module = sys.modules[modulename]
module = __import__(modulename)
return getattr(module, classname)
print getClass("WichmannHill", "random")
print getClass("WichmannHill", "random")()
More information about the Python-list