I have come across a situation that I believe has revealed a gap in my understanding of how references work in Python.
Suppose that we have two classes:
class A:
def __init__(self):
self.x = [1,2,3]
def modify(self):
self.x.append(4)
def reset(self):
self.x = []
class B:
def __init__(self, x):
self._x = x
def say(self):
print self._x
a = A()
b = B(a.x)
b.say()
a.modify()
b.say()
a.reset()
b.say()
The output I expected was:
[1, 2, 3]
[1, 2, 3, 4]
[]
The output I got was:
[1, 2, 3]
[1, 2, 3, 4]
[1, 2, 3, 4]
It seems that when I called reset() and set self.x to a new list, the reference held by B became independent and lived on, thereby becoming a copy instead of a reference. Is this a correct understanding?