I understand that in python every thing, be it a number, string, dict or anything is an object. The variable name simply points to the object in the memory. Now according to this question,
>> a_dict = b_dict = c_dict = {}
This creates an empty dictionary and all the variables point to this dict object. So, changing any one would be reflected in the other variables.
>> a_dict["key"] = "value" #say
>> print a_dict
>> print b_dict
>> print c_dict
would give
{'key': value}
{'key': value}
{'key': value}
I had understood the concept of variables pointing to objects, so this seems fair enough.
Now even though it might be weird, since its such a basic statement, why does this happen ?
>> a = b = c = 1
>> a += 1
>> print a, b, c
2, 1, 1 # and not 2, 2, 2
First part of question: Why isn't the same concept applied here ?
Actually this doubt came up when I was trying to search for a solution for this:
>> a_dict = {}
>> some_var = "old_value"
>> a_dict['key'] = some_var
>> some_var = "new_value"
>> print a_dict
{'key': 'old_value'} # and not {'key': 'new_value'}
This seemed counter-intuitive since I had always assumed that I am telling the dictionary to hold the variable, and changing the object that the variable was pointing to would obviously reflect in the dictionary. But this seems to me as if the value is being copied, not referenced. This was the second thing I didn't understand.
Moving on, i tried something else
>> class some_class(object):
.. def __init__(self):
.. self.var = "old_value"
>> some_object = some_class()
>> a_dict = {}
>> a_dict['key'] = some_object
>> some_object.var = "new_value"
>> print a_dict['key'].var
"new_value" # even though this was what i wanted and expected, it conflicts with the output in the previous code
Now, over here, obviously it was being referenced. These contradictions has left me squacking at the unpredictable nature of python, even though I still love it, owing to the fact I don't know any other language well enough :p . Even though I'd always imagined that assignments lead to reference of the object, however these 2 cases are conflicting. So this is my final doubt . I understand that it might be one those python gotcha's . Please educate me.
See Question&Answers more detail:
os