Question: lists in classes

Stephan Houben stephan at pcrm.win.tue.nl
Mon Aug 30 03:55:00 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].

Sure, `b' has not been modified. However, a.list and b.list are
both references to the same list object. You changed the object
through a.list, so now b.list reflects the change as well.
 
> How would I tell python that I only want to _define_ the class, not
> instantiate it?

Everything you put directly in the class body is executed when the
class is defined. If you want to perform something when an instance
is created, put it in the class' __init__ method.

The following gives the behaviour you probably expect:

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

Now a.list and b.list are distinct objects.

Greetings,

Stephan





More information about the Python-list mailing list