Generating Multiple Class Instances

Julie Torborg jtorborg at fnal.gov
Thu Jun 7 17:13:56 EDT 2001


>

We have a winner! D-man's code most closely resembles what I want to do:

>
> flavor_list = ['up', 'down', 'strange', 'charm', 'top', 'bottom']
> flavor = {}
> for each in flavor_list :
>     flavor[ each ] = Quark()
>
> Here I start with the list of flavors, represented as strings
> (interesting flavors...must be a different language <grin>).  I
> iterate through that list and add a new instance of the Quark class to
> a dictionary.  The key to the dictionary is the flavor.
>
> Later you can
>
> 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

extracting a single element.  This is something I haven't been able to get
most other suggested code to do, though I'm still looking into all the
suggestions.

> An alternative solution would be to store the name of the flavor in
> the instance of the Quark class.  It could be an argument to __init__.
>
> 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.

Thanks for the assist.





More information about the Python-list mailing list