I just got owned. I couldn't believe that this was true, but upon testing it, I found it to be:
class A(object):
v = []
a = A()
b = A()
What do you think that the following code will return?
a.v is b.v
What about this code?
a.v.append(1)
a.v[0] == b.v[0]
Sure enough, a.v is b.v
, they both share the same reference to the same list. Coming from a, well, every other programming language background, how does this make sense?
In Java, if I were to write a class like this:
class A {
public Object[] v = new Object[]{};
}
...I would never, in my wildest dreams, think that two instances of the class would share the same reference to the array.
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?