This is my second day of learning python (I know the basics of C++ and some OOP.), and I have some slight confusion regarding variables in python.
Here is how I understand them currently:
Python variables are references (or pointers?) to objects (which are either mutable or immutable). When we have something like num = 5
, the immutable object 5
is created somewhere in memory, and the name-object reference pair num
is created in a certain namespace. When we have a = num
, nothing is being copied, but now both variables refer to the same object and a
is added to the same namespace.
This is where my book, Automate the boring stuff with Python, confuses me. As it's a newbie book, it doesn't mention objects, namespaces, etc., and it attempts to explain the following code:
>>> spam = 42
>>> cheese = spam
>>> spam = 100
>>> spam
100
>>> cheese
42
The explanation it offers is exactly the same as that of a C++ book, which I am not happy about as we are dealing with references/pointers to objects. So in this case, I guess that in the 3rd line, as integers are immutable, spam
is being assigned an entirely new pointer/reference to a different location in memory, i.e. the memory that it was initially pointing to wasn't modified. Hence we have cheese
referring to the initial object referred to by spam
. Is this the correct explanation?
42
inspam
, Now you storedspam
in cheese meanscheese = 42
, After that you replacedspam
to100
, You didn't editedcheese
that is whycheese
is still42
.spam
on the number 42. Next, you stuck the labelcheese
on the thing labelled asspam
(not on top of the label itself, mind you). Then you peeled thespam
label off of that and put it on the number 100.