Can you create a class from a string name
Alex Martelli
aleax at aleax.it
Sat Mar 1 17:28:03 EST 2003
Vivek Sawant wrote:
> is there a way to create a class object or an instance object for a
> class if you have the name of the class as a string at the runtime.
>
> For example, in Java you can create a 'Class' object as:
>
> Class.forname ('<classname>')
In Python, what you load are *modules*, and classes (as well as
everything else) live in modules. This is somewhat different from the
Java approach where classes are "directly loaded".
So, to "load and access" a class from a name, in Python you need
two steps, and two names:
-- a module name, which you will use to load the module (or to
access it if it's already loaded);
-- a class name within the module.
def forname(modname, classname):
module = __import__(modname)
classobj = getattr(module, classname)
return classobj
Note that, while I've used "classname" and "classobj" here, this is
NOT at all limited to classes -- it will access just as well any module
attribute at all, be it a class, a function, a number, whatever.
In practice one might be less didactic and more concise and generic:
def forname(modname, attname):
return getattr(__import__(modname), attname)
Alex
More information about the Python-list
mailing list