[Tutor] Instantiating large numbers of objects?

Kirby Urner urnerk@qwest.net
Sun, 03 Feb 2002 14:12:06 -0800


>
>So far this is the only way I know of to instantiate classes.
>Obviously when a bank uses this software, they wouldn't open
>up the code to add new accounts. How would they create new
>instances of the Account class? I seem to recall being told
>once that in C or Java one would create an array or Vector of
>objects. I was thinking I would do the same thing with my
>Rooms, except Python doesn't have arrays or Vectors.

Lists are pretty much the same thing.  You access a list's
elements by number, same as an array, starting from 0.  But
it seems sort of arbitrary to use numbers if you also have
names handy.  A dictionary lets you add an arbitrary number
of objects and retrieve them by name, vs. number.  Since
order doesn't matter (why should the kitchen be a lower
number than the bathroom), you've got another point in
favor of using a dictionary.

But didn't you post this question earlier, and get a number
of responses e.g. from Lloyd Kvam, Karthik Gurumurthy, and
myself?  Here's an excerpt from an earlier reply:

   params = [ ("great hall","where trolls live",3),
             ("dungeon","not a fun place",0),
             ("tower room","where she sleeps",1)]

   listofRooms = []

   for p in params:  listofRooms.append(apply(Rooms,p))

Again, if you want to create a number of objects in a list,
you can do it like this:

      listofrooms = []  # empty list
      for r in ["kitchen","hallway"...]:
         listofrooms.append(Room(r))

As was shown earlier, if your constructor expects three
variables, and you have 3-tuples or 3-argument lists, you
can use apply(function,tuple) for class definitions as
well.  apply gets around have to do something like:
function(mytuple[0],mytuple[1],mytuple[2]) -- you just
go apply(function,mytuple) instead.

      listofrooms = []
      rooms = [('kitchen','place to eat',2),('hallway','long',3)...]
      for r in rooms:
           listofrooms.append(apply(Room,r))

The dictionary option is similar:

      dictofrooms = {}
      rooms = [('kitchen','place to eat',2),('hallway','long',3)...]
      for r in rooms:
           dictofrooms[r[0]] = apply(Room,r)

something like that.

The end result is you have a bunch of room objects stored
in either a list or dictionary (= Java hashtable).


>I apologize if I'm not explaning myself clearly. This is
>still pretty new to me and I'm not 100% sure how to phrase my
>question. Hopefully the readers of this list are smart enough
>to figure out what I'm saying though! ;)
>
>Britt

It's not that you're unclear, it's just that you asked before,
and people answered, so I was assuming you were after some
different kind of information.

Kirby