Entry
How can I create an object instance giving its classname at runtime?
Feb 11th, 2008 19:28
Gabriel, unknown unknown, Nathan Wallace, Alex, Emile van Sebille, Manus Hand, Michal Wallace
This sort of thing works:
>>> class C: pass
...
>>> c = eval ('C') ()
>>> c
<__main__.C instance at 103e18>
>>>
-----OR TRY-----
You could also play with changing the instance's class or bases
attributes, e.g.:
>>> class T1:
def __repr__(self):
return "T1"
>>> class P1:
def __repr__(self):
return "P1"
>>> a = P1()
>>> a
P1
>>> a.__class__ = T1
>>> a
T1
--- or try things like:
>>> class T3:
def __str__(self):
return "T3"
>>> a.__class__.__bases__=(T3,)
>>> a
T1
>>> print a
T3
----OR TRY----
After dynamically realizing that "object" should be an instance of a
particular "className" found in a certain "moduleName":
code = __import__(moduleName)
object = getattr(code, className)(initParam1, initParam2, etc.)
----OR TRY----
>>> class C:
... pass
...
>>> def makeNew(className):
... return globals()[className]()
...
>>> makeNew('C')
<__main__.C instance at 80dac50>