python bug?

Peter Hansen peter at engcorp.com
Mon Jul 26 15:28:55 CEST 2004


Anthony Petropoulos wrote:

> When running this simple code:
> -------
> class Dada:
>         a = []

This defines a class variable, of which there exists
only one, effectively shared across all instances of
Dada.

>         def __init__(self, arg):
>                 self.a.append(arg)

This (the "self.a" part) looks up the name "a" in the
dictionary for the instance.  It doesn't find anything
there, so it looks next in the class.  It finds the
shared class variable.  Then you append something to
it.  Note that as you are not "rebinding" the name
"self.a" to anything, but merely modifying the contents
of the list it is bound to, you don't end up with an
instance variable called "self.a".

> d1 = Dada("pro")
> d2 = Dada("hoho")

Given the above, it should be apparent that this is
just appending both values to the same list.

> Is this a feature? Is there something I'm missing?

Yes, you are missing the following change to your code
to do what you want:

class Dada:
     def __init__(self, arg):
         self.a = []
         self.a.append(arg)

(of course, you would probably just write that as a
single line "self.a = [arg]" in real code)

This stuff should be covered, I believe, by the tutorial.
Make sure you have gone through that carefully, and perhaps
take the time to read all the FAQ entries before getting too
deep into the language.

-Peter



More information about the Python-list mailing list