Python class instantiation using name

Terry Reedy tjreedy at udel.edu
Tue Dec 17 17:55:33 EST 2002


"Amol P Dharmadhikari" <ad at cs.usfca.edu> wrote in message
news:mailman.1040161163.380.python-list at python.org...
> Is it possible to create an instance of a class using its name?
> If so how?

Depends on what you mean be 'its name': definition name (.__name__) or
name bound to the class in the current namespace.  Consider

>>> class C:pass
...
>>> B=C; del C
>>> B.__name__
'C'
>>> b=B()
>>> c=C
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
NameError: name 'C' is not defined


> So in general, if I have a string which contains the name of a
class,
> how do I create an instance of that class?

>>> classname='B'
>>> bw=eval(classname+'()')
>>> b;bw
<__main__.C instance at 0x007E3C80>
<__main__.C instance at 0x007E4740>

> Please cc me in the reply as I am not subscribed to the list.
Since you apparently gave a real email address, done.

Terry J. Reedy





More information about the Python-list mailing list