The simple answer is that all variables in python are references. Some references are to immutable objects (such as strings, integers etc), and some references are to mutable objects (lists, sets). There is a subtle difference between changing a referenced object's value (such as adding to an existing list), and changing the reference (changing a variable to reference a completely different list).
In your example, you are initially x = o.a
making the variable x
a reference to whatever o.a
is (a reference to 1
). When you then do x = 2
, you are changing what x references (it now references 2
, but o.a
still references 1
.
A short note on memory management:
Python handles the memory management of all this for you, so if you do something like:
x = "Really_long_string" * 99999
x = "Short string"
When the second statement executes, Python will notice that there are no more references to the "really long string" string object, and it will be destroyed/deallocated.