Generating Multiple Class Instances

D-Man dsh8290 at rit.edu
Wed Jun 6 17:05:55 EDT 2001


On Wed, Jun 06, 2001 at 03:28:33PM -0500, Julie Torborg wrote:
| I'm no wiz at OOP, but I have the following problem:
| 
| I have a list of some hundreds of items, each of which has several
| attributes,What I want to do is peg each of the values to the list item
| and move it around my program.  This seems like the perfect opportunity
| to take advantage of the OOP aspect of Python by setting up a class, but
| I can't create or use instances without hard-wiring it for every list
| item.  What I want to do is:
| 
| class Quark:
|     def __init__(self):
|         self.color=getcolor()
|         self.mass=getmass()
| 
| flavor=['up', 'down', 'strange', 'charm', 'top', 'bottom']
| for each in flavor:

Here you create a new local name that is bound to each element in the
list 'flavor' in succession.

|     each=Quark()

Here you rebind it to a new instance of the Quark class.  Each
iteration creates, then releases a new instance of the Quark class.

| ###Then later:
| for each in flavor:
|     print each.color

'flavor' is still just a list of strings, it hasn't been changed.

| ###What I'm relegated to doing is:
| 
| up=Quark()
| down=Quark()
| strange=Quark()...
| 
| print up.color
| print down.color
| print strange.color...
| 
| Which works, but with hundreds of list items, gets messy in a hurry.
| I've also tried messing around with using something that looks more like
| quark=Quark() several times, but then all the info stored in the
| previous instance gets obliterated.  I've also tried using lists and
| dictionaries, but they're bulky and what's the point of using an OOP
| language if there's no additional functionality or elegance?

Try this instead :

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.


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


If this isn't clear enough to you, just ask again and mention which
parts aren't clear :-).

-D





More information about the Python-list mailing list