Python — Reference
A good understanding of Python reference
In Python, a variable is not a label of value like you may think. Instead, a reference in python means a different name for a memory location that has been associated. This means an entity allocated with some memory will be referenced with a different name other than the actual name of the memory.
The processing of variables in Python is very different from other languages. Variables in Python have a special attribute: identity
, that is, “identity identification”. This special property is also called “reference” in many places.
How do References Work in Python?
Let’s first take a look at one example: in languages such as C++, variable declaration and assignment can be separated:
int a;
a = 343;
But in python, you must perform assignment operations when declaring python variables
a = 343
If you directly use a variable that does not exist, an error will occur, NameError: name ‘a’ is not defined
In Python, when a = 343
is executed, it first creates the object 343
in memory, and then let a
point to it, which is the reference. Like in the following diagram: