Bug or feature?

Tom Bryan tbryan at zarlut.utexas.edu
Fri May 14 08:50:51 EDT 1999


Michael Hudson wrote:
> 
> landrum at foreman.ac.rwth-aachen.de (Gregory A. Landrum) writes:
> 
> [encounters the hoary old class data problem]
> >
> > So, if I initialize an array variable within the "class scope" (for
> > want of knowing the proper word) by simple assignment, this same array
> > is shared between *all* instances of the class.  If I do the same
> > initialization within a class method (like __init__), then each
> > instance has its own copy of the array.  I like the second case much
> > better... having the array shared between all instances just strikes
> > me as wrong.
> >
> > If this behavior is indeed what is intended, I'm really curious to
> > know why.  Why is this confusing (to me at least) behavior considered
> > desirable?
> 

[...Michael explains some technical stuff...]

I thought the poster was asking a simpler question.

My answer:

1. Usually, you want to declare data members in a class's 
__init__ method.  Then every object gets its own copy of the 
initialized data member.  As you showed, modifications to the data 
held by one instance don't affect the data (initialized in __init__)
of another  method.

2. Sometimes it is useful/necessary to save state or share information
among all instances of a certain class.  One way to do that is to 
declare a mutable data structure, such as your data1, at the class 
level.  Then all instances can modify this shared data, and other 
instances will immediately see the updates.  

If you know other OO languages, you may have heard of this distinction 
as instance members (case 1) and class members (case 2).

Perhaps others would like to post some examples of when they've 
actually neede the technique in Answer 2 in their Python programs to
give you an idea of when you might need this *feature*.

If you don't specifically want the behavior of class data (case 2), 
then you need to declare/initialize all (mutable) data members in 
__init__.

-- 
tbryan at zarlut.utexas.edu
Remove the z from this address to reply.
Stop spam!  http://spam.abuse.net/spam/




More information about the Python-list mailing list