Generating Multiple Class Instances

D-Man dsh8290 at rit.edu
Thu Jun 7 18:18:28 EDT 2001


On Thu, Jun 07, 2001 at 04:13:56PM -0500, Julie Torborg wrote:
| We have a winner! D-man's code most closely resembles what I want to do:

Thanks.

| > flavor_list = ['up', 'down', 'strange', 'charm', 'top', 'bottom']
| > flavor = {}
| > for each in flavor_list :
| >     flavor[ each ] = Quark()
| >
| > for name , value in flavor.items() :
| >     print  name , ":" , value.color
| >
| > To print out the names and their associated value.
| 
| This way, I can also have a line:
| 
| print flavor['up'].color
| 

Yes.  This is also quite fast because dictionary lookups are fast.

| > class Quark :
| >     def __init__( self , name ) :
| >         self.name = name
| >         <...>
| >
| > flavor_list = ['up', 'down', 'strange', 'charm', 'top', 'bottom']
| > flavor = []
| > for name in flavor_list :
| >     flavor.append( Quark( name ) )
| > del flavor_list # not needed anymore
| >
| > for item in flavor :
| >     print  item.name , ":" , item.color
| 
| I like this too, but I think it suffers from the problem above.  To access
| the color of the top, I have to know the place of the "top" instance in the
| list  (called "topindex" below)...
| 
| print flavor[topindex].color
| 
| ...the whole point is so that I don't have to remember where each guy is in
| the list.

You mentioned that this is going to be in a GUI at some point.  If you
have, say, a list  (gtk_list, javax.swing.JList, whatever) with all
the items in it then the item would probably want to know its name.
Also you would already have a reference to the object and you wouldn't
need to look for it in the list.  (you would ask the gui list object
what item is selected when a button is pressed, or something and it
would return the object back to you.  You no longer need the 'flavor'
list)

Another alternative would be to combine the two techniques :

class Quark :
    def __init__( self , name ) :
        self.name = name
        <...>

flavor_list = ['up', 'down', 'strange', 'charm', 'top', 'bottom']
flavor = {}
for name in flavor_list :
    flavor[ name ] = Quark( name )
del flavor_list # not needed anymore


Then you could still do

print flavor[ "up" ].color

or you could

print flavor[ "up" ].name , ":" , flavor[ "up" ].color


I'm assuming the key won't be a string literal, of course ;-).

-D





More information about the Python-list mailing list