dictionary containing instances of classes behaving oddly

Ben Benjamin.Barker at gmail.com
Thu Dec 28 14:37:39 EST 2006


Yes- I can see that  my_list and mops, being outside def __init__()
only get created once, hence the confusion.

Surely def __init__() gets called each time an instance is created
however? But the snag is that if they have default values set these are
shared between all instances, even if they are, for instance, lists...?

Cheers,

Ben


Thanks.
Erik Johnson wrote:

> "Ben" <Benjamin.Barker at gmail.com> wrote in message
> news:1167333218.447246.236960 at h40g2000cwb.googlegroups.com...
>
> > class record:
> >         my_list =[]
> >         mops=[]
> >
> >         def __init__(self,mops):
> >                 self.mops=mops
>
> Similar to the example I gave, the lists my_list and mops shown above are
> executed just once: when your class definition is first parsed.
> The statement:
>
> def __init__(self,mops):
>
> is also executed just once, and the value for mops at that time is the value
> assigned to object attributes during object construction - a reference to
> record.mops, in your case.  So, there are really only two lists here, class
> attributes record.my_list and record.mops.  Each of your constructed objects
> is assigned a reference to record.mops.  They all share that list.  If you
> want a record object to have it's own list, give it a new, empty one and
> then populate it appropriately.




More information about the Python-list mailing list