[Python-au] Class attribute behaviour wierdisms

Graham Dumpleton grahamd at dscpl.com.au
Tue Feb 21 05:26:24 CET 2006


Darryl Ross wrote ..
> Hey All,
> 
> Just wondering whether this would be expected behaviour??

Yes.

> > darryl at mail:~$ cat test.py
> > class Blah:
> >     attr = []

The "attr" variable in this case is common to all class instances.
If you want one specific to an instance, create and initialise it
in the constructor:

class Blah:
  def __init__(self):
    self.attr = []

> > for i in range(10):
> >     obj = Blah()
> >     obj.attr.append('123')
> >     print obj.attr
> 
> 
> > darryl at mail:~$ python test.py
> > ['123']
> > ['123', '123']
> > ['123', '123', '123']
> > ['123', '123', '123', '123']
> > ['123', '123', '123', '123', '123']
> > ['123', '123', '123', '123', '123', '123']
> > ['123', '123', '123', '123', '123', '123', '123']
> > ['123', '123', '123', '123', '123', '123', '123', '123']
> > ['123', '123', '123', '123', '123', '123', '123', '123', '123']
> > ['123', '123', '123', '123', '123', '123', '123', '123', '123', '123']
> 
> 
> I would have thought that by instantiating a new object, it should be a
> copy of the definition, not a reference to the previous object?
> 
> Any ideas?
> 
> Regards
> Darryl



More information about the python-au mailing list