Dynamic creation of an object instance of a class by name

Peter Abel PeterAbel at gmx.net
Wed Apr 7 16:24:43 EDT 2004


Andre Meyer <meyer at acm.org> wrote in message news:<mailman.419.1081348862.20120.python-list at python.org>...
> 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

I'm not quite sure if I guess what you mean:
Is it?
>>> class A:
... 	def __init__(self,id):
... 		self.id=id
... 	def getID(self):
... 		print self.id
... 
>>> a=eval('A')('item')
>>> a.getID()
item

Or rather the following?

>>> classNEW=new.classobj('classX',(A,),globals())
>>> x=classNEW('another_item')
>>> x.getID()
another_item
>>> 

The first one evaluates the string 'A' to a class-object from
which you can instantiate.
>>> eval('A')
<class __main__.A at 0x00DFA540>
>>> 

The second one inherits classNEW() from A() with name 'classX'
with the namespace of globals().
>>> classNEW
<class __main__.classX at 0x00DF6D80>
>>> classNEW.__name__
'classX'
>>> 
where the name of class A() is 'A'
>>> A.__name__
'A'

See http://www.python.org/doc/2.2.3/lib/module-new.html
...
classobj(name, baseclasses, dict) 
This function returns a new class object, with name name, derived from
baseclasses (which should be a tuple of classes) and with namespace
dict.

Regards
Peter



More information about the Python-list mailing list