Dynamic creation of an object instance of a class by name

Jacek Generowicz jacek.generowicz at cern.ch
Wed Apr 7 11:45:47 EDT 2004


meyer at acm.org (Andre Meyer) writes:

> Hi all
> 
> 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!)

I'm sorry, I can't for the life of me figure out what the (semantic)
difference is between "intsance of a class" and "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', (), {})

This creates a new class which will be called "A", displacing your
original class by the same name.

> 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!!!

Yes, they produce an instance of your newly created class.

> How can I get a new object instance???

I think you mean to ask "How can I get a new instance of the class
whose name I have in a string?". In other words, you should be asking
yourself, "How can I get my hands on an object whose name[*] I have in a
string?" (One possible approach is shown below.)

> What else needs to be filled in for base_classes and __dict__ in
> new.classobj?

You can't do it that way ... that way you create a _new_ separate
class called "A".

Here's how you might achieve what you want:

>>> class A:
...     def __init__(self, id):
...        self.id = id
...     def getID(self):
...       print self.id
... 
>>> oa1 = globals()['A'](12345)
>>> oa1
<__main__.A instance at 0x8190844>
>>> oa1.getID()
12345
>>> 


[*] I'm a bit wary about using "name" here, because I don't really
    mean the name of the class, but the name of a variable that
    happens to refer to the class.
    
    For example, consider (in the context established above)
    
    >>> B = A
    >>> del A
    >>> B.__name__
    'A'
    >>> A.__name__
    Traceback (most recent call last):
      File "<stdin>", line 1, in ?
    NameError: name 'A' is not defined
    
    So, while the name of the class is still "A", it is no longer
    known by an identifier of that name.



More information about the Python-list mailing list