[Tutor] Dynamic creation of class instances...

Andrei Kulakov ak@silmarill.org
Tue, 21 May 2002 18:29:45 -0400


On Tue, May 21, 2002 at 01:59:23PM -0700, Israel Evans wrote:
> Hello All...
>  
>             I'm attempting to dynamically create an unknown number of class
> instances and I'm wondering if there is a better way.  Right now I start out
> with a list of names, craft a string that looks like a class instantiation
> and then exec the sucker.  After that I think I just have to "know" which
> objects I've just created, add them to a list and then for loop over the
> list to add them to a dict so that I can easily access them.  Unfortunately
> I think when I add the objects to the dict I'm making the key an instance of
> the class as well as the value. 
>  
> >>> class Test:
>             def __init__(self):
>                         pass
>  
> >>> namelist = ["kaya", "felice", "chalma", "frisia"]
>  
> >>> for name in namelist:
>             thestring = '%s = Test()'%(name)
>             exec(thestring)
>  
> >>> kaya
> <__main__.Test instance at 0x0093E1A8>
>  
> >>> oblist = [kaya, felice, chalma, frisia]
>  
> >>> for obj in oblist:
>             obdict[obj] = obj
>             
> >>> obdict[kaya]
> <__main__.Test instance at 0x0093E1A8>
>  
> Any Ideas?
> ps. exec() scares me.
>
You don't need that here.. I think.

>>> mydict = {}
>>> for item in lst:
...  mydict[item] = T()
... 
>>> mydict['kaya']
<__main__.T instance at 0x80df2d4>

It's not clear to me how you plan to use these objects.

 - Andrei
>  
> Thanks,
>  
>  
>  
> ~Israel~
>  

-- 
Cymbaline: intelligent learning mp3 player - python, linux, console.
get it at: cy.silmarill.org