Dynamic creation of an object instance of a class by name

Peter Otten __peter__ at web.de
Wed Apr 7 11:41:48 EDT 2004


Andre Meyer wrote:

> I have been searching everywhere for this, but have not found a
> solution, yet.
> 
> What I need is to create an object that is an instance of a class (NOT a
> class instance!) of which I only know the name as a string. This what I
> tried:
> 
> class A:
>     def __init__(self, id):
>        self.id = id
>     def getID(self):
>       print self.id
> 
> ca = new.classobj('A', (), {})
> oa1 = ca()
> oa2 = new.instance(ca)
> 
> oa1
> <__main__.A instance at 0x007E8AF8>
> 
> oa1.getID()
> Traceback (most recent call last):
>    File "<stdin>", line 1, in ?
> AttributeError: A instance has no attribute 'getID'
> 
> oa2
> <__main__.A instance at 0x007E8AF8>
> 
> oa2.getID()
> Traceback (most recent call last):
>    File "<stdin>", line 1, in ?
> AttributeError: A instance has no attribute 'getID'
> 
> 
> Thus, both ways only produce a class instance, but NOT an object of that
> class!!! How can I get a new object instance???
> What else needs to be filled in for base_classes and __dict__ in
> new.classobj?
> 
> 
> Any help is appreciated, this is driving me nuts!
> 
> kind regards
> Andre

Don't listen to the voices whispering "Use eval()" or "globals() are the way
to go", make it clean and explicit with a dictionary containing all classes
you want to expose:

>>> class A: pass
...
>>> class B: pass
...
>>> class C: pass
...
>>> exposed = dict(A=A, B=B, C=C)
>>> exposed["A"]()

:-)

Peter




More information about the Python-list mailing list