Question: lists in classes

Michael Hudson mwh21 at cam.ac.uk
Mon Aug 30 03:51:43 EDT 1999


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

> Apologies if this has been answered before...

Just a few times, yes. This problem seems hard to categorise and so
difficult to search deja or the FAQ for (is there an entry in the FAQ
for this? I can't find it!).
 
> class foo:
>     list=[]

This makes `list' a *class* variable, not an instance variable.

You want to write:

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

instead. This bites almost everyone at some point I think. It
certainly bit me.

> 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?

Um, don't really understand what you're asking here. 

To understand what's going on, you should understand that the class
body is executed when the interpreter reads it, not when the class is
created. This can be used to erform some sneaky dynamic hacks, but
most of the time it just does what you want.

you'll-get-used-to-it-ly y'es - Michael




More information about the Python-list mailing list