Mutable class attributes are shared among all instances, is it normal ?
Alain TESIO
alain at onesite.org
Thu Jun 7 18:17:46 EDT 2001
Hi, sometimes class attributes added just after
"class ...:" outside a functions interfere among
instances, more precisely mutable objects are
linked to the same object as if it were a static
attribute.
See the test case below.
If I delete the line "val=[None]" in class
Y and add "self.val=[None]" in its __init__
it works as class X.
Is it a bug or did I miss something ?
I'm using Python 2.1, it has the same behaviour
on Linux and Windows.
Alain
============ start of file 'cl.py'
import random
class X:
val=None
def __init__(self):
for i in range(3):
self.val=random.random()
def __repr__(self):
return str(self.val)
class Y:
val=[None]
def __init__(self):
self.val[0]=random.random()
def __repr__(self):
return str(self.val)
============ end of file 'cl.py'
21:56:03 observer ~ $python
Python 2.1 (#2, Apr 30 2001, 22:51:42)
[GCC 2.95.2 20000220 (Debian GNU/Linux)] on linux2
Type "copyright", "credits" or "license" for more information.
>>> import cl
>>> x1=cl.X()
>>> x2=cl.X()
>>> x1
0.395920790054
>>> x2
0.691535797136
>>> y1=cl.Y()
>>> y2=cl.Y()
>>> y1
[0.078289390442599416]
>>> y2
[0.078289390442599416]
>>>
More information about the Python-list
mailing list