Question: lists in classes

Fredrik Lundh fredrik at pythonware.com
Mon Aug 30 03:46:49 EDT 1999


Jeff Turner <jturner at ug.cs.su.oz.au> wrote:
> Apologies if this has been answered before...

it has...
 
> class foo:
>     list=[]
> 
> a=foo()
> b=foo()
> a.list.append(123)
> print b.list
> 
> I would expect the above code to return "[]", since b has not been
> modified since instantiation.

but it has.  a.list is a class attribute, and are
modified in place.

> However it returns [123].

> How would I tell python that I only want to _define_ the class, not
> instantiate it?

use an __init__ method, just like the rest of us ;-)

> class foo:
>     def __init__(self):
>         self.list=[]

also see:
http://www.python.org/doc/FAQ.html#6.24
http://www.python.org/doc/FAQ.html#6.25

and perhaps
http://www.python.org/doc/FAQ.html#4.84

</F>





More information about the Python-list mailing list