[Tutor] Dynamically instantiating objects?

Jeff Shannon jeff@ccvcorp.com
Fri, 12 Apr 2002 10:06:32 -0700


> Israel Evans <israel@lith.com> wrote:

> I'm trying to instantiate a number of objects from a list.
> Say for example I have three names in a list and I want an object created
> that uses the names from that list as the name of that instance.
> ###
> names = ['maude', 'claire', 'eudelle']
>
> class pip:
>             def __init__(self, name, number):
>                         self.name = name
>                         self.number = number
>
> for name in names:
>             name = pip(name, number)
> ###

[...]

What I would do in this case, is store your objects in a dictionary.  Given the
above class pip, if you instantiate them this way:

pips = {}
for name in names:
    pips[name] = pip(name, number)

Then you can refer to them whenever you need them as

pips['maude'].dosomething()
# or
name = 'claire'
pips[name].dosomething()
# or even
for name in pips.keys():  #if using Py2.2--for name in pips:
    pips[name].dosomething()
for each in pips.values():
    each.dosomething()

It *is* possible to create each name in your list as a global variable name,
using exec, but it really isn't recommended, and 99% of the time using a
dictionary or other collection will make your code cleaner and more sensible
anyhow.

Jeff Shannon
Technician/Programmer
Credit International