Question: lists in classes
stephan at pcrm.win.tue.nl
Mon Aug 30 09:55:00 CEST 1999
Jeff Turner <jturner at ug.cs.su.oz.au> writes:
> Apologies if this has been answered before...
> class foo:
> print b.list
> I would expect the above code to return "", since b has not been
> modified since instantiation. However it returns .
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:
self.list = 
Now a.list and b.list are distinct objects.
More information about the Python-list