Dynamic creation of an object instance of a class by name

Andre Meyer meyer at acm.org
Wed Apr 7 10:22:42 EDT 2004


Hi all

I have been searching everywhere for this, but have not found a solution, yet.

What I need is to create is 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






More information about the Python-list mailing list