Bug or feature?

Michael Hudson mwh21 at cam.ac.uk
Fri May 14 07:43:26 EDT 1999


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? 

It's kind of difficult to make methods work without it.

Y'see when the interpreter reaches a

def meth(self,param):
    ....

statement, it reads the body of the funciton, makes a code object,
wraps this in a function object and bind the name meth to it.

So it's a bit like

meth = lambda self,param: ...

except that lambda only allows an expression in it's body.

So when the interpreter reaches "obj1.data1" in your code, it doesn't
know what you're going to do with the returned attribute - you might
be going to mutate it, store a reference to it or try and call it as a
method. So it looks first for data1 in the objects namespace, then if
it doesn't find it looks it up in the class namespace. If that fails
it goes on to the namespaces of base classes, if any. (If what is
eventually turned up in this fashion is a function it is wrapped up
into an instance method, but that's not really relavent to the
discussion).

If, however, you call "self.data3 = ..." than a new entry is created
in the object's namespace.

You'll get used to this eventually (or just plain ignore it).

HTH
Michael




More information about the Python-list mailing list