85 lines
2.5 KiB
Plaintext
85 lines
2.5 KiB
Plaintext
From: landrum at foreman.ac.rwth-aachen.de (Gregory A. Landrum)
|
|
Date: 14 May 1999 13:16:27 +0200
|
|
Subject: Bug or feature?
|
|
Message-ID: <su2tfc35g.fsf@foreman.ac.rwth-aachen.de>
|
|
Content-Length: 2347
|
|
X-UID: 1815
|
|
|
|
Hi,
|
|
|
|
After spending an hour chasing down a problem in my code last
|
|
night, I ran across something that made me curse. At first I thought
|
|
"Ha! I found a bug!" Then I thought about it a little bit more and
|
|
decided "Mabye it's a feature." Then I thought about it a little more
|
|
and realized that I can think of no good reason for this "feature"
|
|
to exist. Now I'm posting in hopes of obtaining enlightenment.
|
|
|
|
Here's a short section of code which demonstrates the "problem":
|
|
|
|
#----------------------------
|
|
class hasarray:
|
|
data1 = [1,2,3];
|
|
|
|
def __init__(self):
|
|
self.data3 = [1,2,3];
|
|
|
|
|
|
if __name__=="__main__":
|
|
obj1 = hasarray();
|
|
obj2 = hasarray();
|
|
|
|
print "before:";
|
|
print "\tobj1:", obj1.data1,obj1.data3;
|
|
print "\tobj2:", obj2.data1,obj2.data3;
|
|
|
|
obj1.data1[0] = -1;
|
|
obj1.data3[2] = -1;
|
|
|
|
print "after:";
|
|
print "\tobj1:", obj1.data1,obj1.data3;
|
|
print "\tobj2:", obj2.data1,obj2.data3;
|
|
#----------------------------
|
|
|
|
And here's what happens when I run it:
|
|
----------------------------
|
|
foreman ~/python python arrs.py
|
|
before:
|
|
obj1: [1, 2, 3] [1, 2, 3]
|
|
obj2: [1, 2, 3] [1, 2, 3]
|
|
after:
|
|
obj1: [-1, 2, 3] [1, 2, -1]
|
|
obj2: [-1, 2, 3] [1, 2, 3]
|
|
----------------------------
|
|
|
|
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?
|
|
|
|
In case this is actually a bug (I don't think it's likely... this
|
|
seems like a design decision), I've reproduced the behavior on:
|
|
v1.5.1 under AIX 4.2 and linux (2.0.36)
|
|
v1.5.2 under Win95
|
|
|
|
Thanks in advance for any clues!
|
|
|
|
-greg
|
|
|
|
---------------------
|
|
Dr. Greg Landrum (landrumSPAM at foreman.ac.rwth-aachen.de)
|
|
Institute of Inorganic Chemistry
|
|
Aachen University of Technology
|
|
Prof.-Pirlet-Str. 1, D-52074 Aachen, Germany
|
|
|
|
|
|
|
|
|
|
|