Class warfare...

Daniel Dittmar daniel.dittmar at sap.com
Fri Sep 15 11:17:21 EDT 2000


> Is this how it's supposed to be done?

Yes

> Or is there a better way?

In Python 2.0, you can use list comprehension

Daniel

"Larry Whitley" <ldw at us.ibm.com> wrote in message
news:8ptc91$hhk$1 at news.rchland.ibm.com...
> 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