Newbie: Classes and Lists

Peter Hansen peter at engcorp.com
Tue Apr 2 23:04:09 EST 2002


CGH wrote:
> 
> import random
> 
> class Chromosome:
> 
remove this:
>     data = []
> 
>     def __init__(self, length):
add this:
          self.data = []
>         for bit in range(length):
>             self.data.append(random.randrange(0,2,1))

> I want to define a population of 100 chromosomes. But instead of a list of
> Chromosome objects I seem to get one big (100 x 20) list of 0s and 1s.
> Clearly I've misunderstood something fundamental here. Any help would be
> appreciated.

Yes, you've misunderstood something fundamental: instance variables
instead of class variables.  Basically, your "data = []" was
creating a single field 'data' which was associated with the _class_,
not with a single instance.  When you referenced it with self.data,
Python implicitly used the class variable instead of complaining.
(Perhaps this violates Python's more regular rule of explicit being
better than implicit?  Not sure...)

You need to create instance variables like that by explicit
use of "self.data" (or whatever) in the __init__ method of
the class.  Then each instance gets its own self.data list.

-Peter



More information about the Python-list mailing list