Generating Multiple Class Instances

Paul Prescod paulp at ActiveState.com
Wed Jun 6 17:01:20 EDT 2001


Julie Torborg wrote:
> 
 >  What I want to do is:
> 
> class Quark:
>     def __init__(self):
>         self.color=getcolor()
>         self.mass=getmass()
> 

There's something funny there. How does each Quark know what its color
and mass is? What is the definition of getcolor and getmass? A more
common solution is:

class Quark:
     def __init__(self, color, mass):
        self.color=color
        self.mass=mass

But I guess you've already got this part working....

> ...
>
> flavor=['up', 'down', 'strange', 'charm', 'top', 'bottom']
> for each in flavor:
>     each=Quark()

You aren't changing the list. You're just reading from it, never writing
to it. Here's a straightforward way to do it:

flavornames = ['up', 'down', 'strange', 'charm', 'top', 'bottom']
flavors = []
for each in flavornames:
	flavors.append(Quark())

for each in flavors:
    print each.color

I still don't know where to get the colors or masses. Also, don't you
want to somehow associate the flavornames with the quarks you create?

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




More information about the Python-list mailing list