Generating Multiple Class Instances

Paul Prescod paulp at ActiveState.com
Wed Jun 6 18:28:24 EDT 2001


Julie Torborg wrote:
> 
>...
> 
> I don't want to change the list, I want to do the same thing as typing
> 
> i_top=Quark(top)
> i_bottom=Quark(bottom)

Okay, that would require defining variables in your local scope which is
weird and probably not a good idea in the long term. A better solution,
as you mentioned later, is to use a dictionary.

Then you access stuff with 

i["top"], i["bottom"] etc.

>...
> This just creates a new ordered array.  If I want to access the mass of
> top, I still have to know where in the array the top instance lives.
> 
> What I want to do, is starting with my original list, is to make another
> list (which is composed of a simple variation on the original list, like
> adding the i_ above).

You say that you don't want another "ordered array" but then you say you
want to make another list. Lists in Python are ordered arrays. If you
want random access to things, you need a dictionary.

>...
> Eventually, all of this will be going into a GUI, and access to all these
> parameters will be very non-linear.  The big idea here is to keep all the
> "attributes" associated with their "objects."  It seems to be so well
> described by the OOP jargon I can't believe I'm having trouble.  

I don't think you're having any trouble with the OO stuff at all.

>...
> But, to be fair, the solution you've provided here is better than what
> I've come up with.  Maybe there's a way to automatically build a
> dictionary that will associate a "name" with each instance.  That still
> seems like a lot of keystrokes, not to mention CPU load during lookup
> (like I said, there are hundreds of list items, I fictionalized this one
> for simplicity), especially when I have a gut feeling that with a little
> finesse, there's a much more elegant solution.  Or there should be.

If you want random access lookup based on names, there is no faster way
than a dictionary. Even if you set up a bunch of global variables like
i_this and i_that, those variables would still go in a Python dictionary
behind the scenes. Python has no problem with looking through thousands
of items in milliseconds. Until you get into hundreds of thousands of
items, I wouldn't worry about performance much.

flavors = []
for each in flavornames:
      flavors[each] = Quark(each)

-- 
Take a recipe. Leave a recipe.  
Python Cookbook!  http://www.ActiveState.com/pythoncookbook




More information about the Python-list mailing list