Class warfare...

Alex Martelli aleaxit at yahoo.com
Fri Sep 15 18:20:34 EDT 2000


"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
    [snip]
> >>> 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?

There are several ways, but the one I would suggest is:

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

b = apply(Bucket, (0,2,0,7,0))


Alex







More information about the Python-list mailing list