Python class instantiation using name

Aahz aahz at pythoncraft.com
Wed Dec 18 12:13:00 EST 2002


In article <mailman.1040161163.380.python-list at python.org>,
Amol P Dharmadhikari  <ad at cs.usfca.edu> wrote:
>
>So in general, if I have a string which contains the name of a class,
>how do I create an instance of that class?
>
>i.e. something similar to what the below java code snippet can do
>Object o = java.lang.Class.forName(className).newInstance()

Given a module M and a class M.C:

    import M
    instance = getattr(M, "C")()

This should be faster than the eval() solutions proposed.
-- 
Aahz (aahz at pythoncraft.com)           <*>         http://www.pythoncraft.com/

"To me vi is Zen.  To use vi is to practice zen.  Every command is a
koan.  Profound to the user, unintelligible to the uninitiated.  You
discover truth everytime you use it."  --reddy at lion.austin.ibm.com



More information about the Python-list mailing list