Question: lists in classes

Timothy R Evans tre17 at pc142.cosc.canterbury.ac.nz
Mon Aug 30 03:40:26 EDT 1999


Jeff Turner <jturner at ug.cs.su.oz.au> writes:

> Apologies if this has been answered before...
> 
> 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. However it returns [123].
> 
> How would I tell python that I only want to _define_ the class, not
> instantiate it?
> 
> Thanks,
> Jeff

The code above adds list as a class attribute, the same list is found
from all instances.  If you want to create an instance, you add it in
the __init__ method as so:

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

a=foo()
b=foo()
a.list.append(123)
print b.list
[]

--
Tim Evans





More information about the Python-list mailing list