Python’s dynamic typing sometimes make people headache, but if you take some time to understand it, you will master it fast.
Here I give some simple samples to try to explain to you the key ideas on how python passes or references objects in between.
1) What happened behind each equal expression
When you do:
a = 3
This expression can be interpreted as:
a -> Name
= -> Reference
3 -> Object
Here 3 is an Object, which are pieces of allocated memory.
Each object has two standard header:
- Type designator
- Reference Counter
2) Shared References and In-Place Changes
a = 3 b = a a = a + 2
In the code above, b will not change with a, because 3 is an integer object which is immutable!
However, if we do
a = [3,4] b = a a = 2
at this time, b do change with a, because [3,4] is a list object which is mutable!
3) “is ” function can be used to test if both are reference to the same object:
L = [1,2,3] M = L L is M # true