Generating Multiple Class Instances

Julie Torborg jtorborg at fnal.gov
Wed Jun 6 16:28:33 EDT 2001


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:
    each=Quark()
###Then later:
for each in flavor:
    print each.color

###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?




More information about the Python-list mailing list