Analysis of Variables in Python
Assignment
In python, variables are just strings that refer to certain objects, which means that they are actually "pointers" in C/C++. When assigning a value to a variable, we actually modifies the reference of the variable:
1 | a = 10 |
The outputs are:
1 | 140723224699976 |
This shows that when creating a
in python, it will bind a
to the address of 10
:
Similarly, when changing the value of a
, we are actually make a
refer to the new value. In addition, when assigning the value of a
to a new variable b
, python does not assign new memory, but just make b
refer to the value of a
:
1 | a = 10 |
The outputs are:
1 | 140722523399240 |
Parameters passing and return
The process of parameters passing is actually a process of assignment. Therefore, what we are passing to the formal parameter a
is the reference of actual parameter b
.
1 | def func(a): |
The outputs are:
1 | 140723839624264 |
Similarly, when returning a value, we are also returning its reference:
1 | def func(): |
The outputs are:
1 | 140723839624008 |
Mutable & immutable objects
In python, everything is an object.
For variables that refer to immutable objects (e.g. string, number, tuple), we can't change the value of objects. When we change the value of variable, we are actually make the variable refer to another object (e.g. fig. 2).
For variables that refer to mutable objects (e.g. list, dictionary), they actually refer to the beginning address of their inner objects, which means variables are "secondary pointers". Therefore, we can change the value of the elements of these objects. Change the value of a variable will also make the variable refer to another object.
1 | a = [1, 2] |
The outputs are:
1 | [2, 2] |
For mutable objects, their member functions may have side effects while member functions of immutable objects will not have side effects but return a new object. The class defined by users is always mutable obejct.