I have read many of the questions posted on variable referencing in Python, but things are still happening as I play with code that I would not expect and its getting quite frustrating. Take this piece of code:
class MyClass(object) :
class_var = "original message" # same for all objects
def __init__(self, instance_var) :
self.instance_var = instance_var #particular to the object
my_object = MyClass("my instance variable")
untouched_object = MyClass("another instance_var")
# Values of class_var and instance_var as expected
MyClass.class_var = "changed message"
# attribute class_var has changed for both objects
# This changes attribute class_var for my_object only
my_object.class_var = "I am my_object"
# THIS ONLY CHANGES ATTRIBUTE CLASS_VAR FOR UNTOUCHED_OBJECT ONLY!
MyClass.class_var = "Last message"
print MyClass.class_var #prints Last Message
print my_object.class_var #prints I am my_object ???
print untouched_object.class_var #prints Last Message
What is going on here? When I create an object of some class with a class variable, it seems that object.class_attribute originally contains a pointer to Class.class_var and I can change the attribute for all objects by assigning to Class.class_var. But if I explicitly assign object.class attribute to some other value, the pointer disappears and altering Class.class_var no longer has an effect on that particular object changing, only all other instances. Is this whats going on here? Further, why would we be able to access and change a class attribute in this way and potentially lose access to a value that the Python Documentation purports is known to all instances?