[Tutor] creating objects in a loop

alan.gauld@bt.com alan.gauld@bt.com
Wed, 3 Apr 2002 13:53:58 +0100


> and I want to do the following:
> 
> >>> cat = Pets('fluffy')
> >>> dog = Pets('fido')
> >>> gorilla = Pets('spike')
> 
> Right now, I can use
> 
> >>> for species,name in petlist:
> ...   exec("%s = Pets('%s')" % (species, name))

Try a dictionary:

pets = {}
for species,name in petlist:
   pets[species] = Pets(name)

Then access them like:

print pets['cat'].name

Alan G.