Class warfare...

Larry Whitley ldw at us.ibm.com
Fri Sep 15 10:38:25 EDT 2000


I'm creating a list of objects and then want to assign the instance
variables in each object different values.  First I tried this:.

class Bucket():
    def __init__(self):
        self.cnt = 0

>>> b = [Bucket()] * 5
>>> b[1].cnt = 2
>>> b[3].cnt = 7
>>> for i in range( 5 ):
>>>    print b[i].cnt
7
7
7
7
7

I expected to see:
0
1
0
7
0

I suspect that my [Bucket()] is producing a reference to the class rather to
an object that is an instance of the class.   So, I changed the b = ...
statement above to:

>>> b = []
>>> for i  in range( 5 ):
>>>    b.append( Bucket() )

And repeat the experiment, I now get what I expected.  Is this how it's
supposed to be done?  Or is there a better way?

Larry





More information about the Python-list mailing list