Terrifying initial values - mutable types share same reference?
<p>I just got owned. I couldn't believe that this was true, but upon testing it, I found it to be:</p>

<pre><code>class A(object):
    v = []

a = A()
b = A()
</code></pre>

<p>What do you think that the following code will return?</p>

<pre><code>a.v is b.v
</code></pre>

<p>What about <em>this</em> code?</p>

<pre><code>a.v.append(1)
a.v[0] == b.v[0]
</code></pre>

<p>Sure enough, <code>a.v is b.v</code>, they both share <em>the same reference</em> to <em>the same list</em>. Coming from a, well, every other programming language background, how does this make sense? </p>

<p>In Java, if I were to write a class like this:</p>

<pre><code>class A {
    public Object[] v = new Object[]{};
}
</code></pre>

<p>...I would never, in my wildest dreams, think that two instances of the class would share the same reference to the array.</p>

<p>My main question is this, is there something equivalent for initial values in Python classes as in Java, C#, etc.? Why do all instances of the class share the same reference to the same list?</p>
