Bug or feature?
Michael Hudson
mwh21 at cam.ac.uk
Fri May 14 09:46:41 EDT 1999
Tom Bryan <tbryan at zarlut.utexas.edu> writes:
> 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.
The poster had already figured out for himself what was going on. He
asked "why is it this way?" - and I don't think it's to support class
data.
> 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.
I have never used this technique. I don't think I've ever seen code
that does. Module-level globals are (IMHO) generally clearer. For a
start, if you want mutable data, you more-or-less have to wrap it up
in a list, and that's confusing.
> 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*.
I don't expect there will be many posts to that effect.
> 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__.
I find object creation generally to be one of the murkier areas of
Python. Supporting more than one method of object construction is a
bit of a pain. One of the few things from C++ I hark for: overloaded
constructors. I guess factory functions are the way to solve this.
everyone-gets-confused-by-this-one-at-some-point-but-the-confusion-
goes-away-quickly-ly y'rs
Michael
More information about the Python-list
mailing list