Mutable class attributes are shared among all instances, is it normal ?

Mats Wichmann xyzmats at laplaza.org
Sat Jun 9 16:17:02 EDT 2001


On Fri, 08 Jun 2001 00:17:46 +0200, Alain TESIO <alain at onesite.org>
wrote:

>Hi, sometimes class attributes added just after
>"class ...:" outside a functions interfere among
>instances, more precisely mutable objects are
>linked to the same object as if it were a static
>attribute.
>
>See the test case below.
>
>If I delete the line "val=[None]" in class
>Y and add "self.val=[None]" in its __init__
>it works as class X.
>
>Is it a bug or did I miss something ?

This is really a FAQ. 

If you define a "variable" in a class outside of a method, it's a
class variable, not an instance variable.  It's a little like using
Java's "static" keyword: you get one copy, shared among all the
instances. Except.... if you go assign to it in a method, you've just
created an instance variable of the same name. (If you want to assign
to a class variable, you need to qualify the reference: X.val)

Play around with the dir() function to see what's happening.

The difference in your two cases:

class X:
    val = None
    def __init__(self):  # assign something to self.val

and

class Y:
    val = [ None ]
    def __init__(self):  # assign something to self.val[0]

Is that in X, you're making a new "val" in the instance.
In Y, you're making a new something in the instance, and making
self.val[0] reference it, but you're not changing the inherited
reference "val". 

-- mats


Mats Wichmann

(Anti-spam stuff: to reply remove the "xyz" from the
address xyzmats at laplaza.org. Not that it helps much...)



More information about the Python-list mailing list