Variables
are created when assigned, can reference
any type of objects
, and must be assigned before they are referenced.
Types live with objects, not vaiables.
a = 3
In the assignment above, python do the following three steps:
x = 123
x = "abc"
x = 123.456
Each time x is assign to a new object, Python reclaims the prior objects's space.
Python will clean up unused space as program runs.
Variables are always pointers to objects, not labels of changeable memory areas.
But, Python's mutable types do in-place object changes.
list1 = [1, 2, 3]
list2 = list1
list1[0] = 4
print(list1)
print(list2)
[4, 2, 3] [4, 2, 3]
The behavior above only occurs for mutable objects that supoort in-place changes.
list3 = [1, 2, 3]
list4 = list3[:]
list3[0] = 4
print(list3)
print(list4)
[4, 2, 3] [1, 2, 3]
The method above support only list type.
The following method works for all mutable types.
import copy
dict1 = {"a": 1, "b": 2}
dict2 = copy.deepcopy(dict1)
dict1["a"] = 3
print(dict1)
print(dict2)
{'b': 2, 'a': 3} {'b': 2, 'a': 1}
list1 = [1, 2, 3]
list2 = list1
print("list1 == list2 :", list1 == list2)
print("list1 is list2 :", list1 is list2)
list1 == list2 : True list1 is list2 : True
list1 = [1, 2, 3]
list2 = [1, 2, 3]
print("list1 == list2 :", list1 == list2)
print("list1 is list2 :", list1 is list2)
list1 == list2 : True list1 is list2 : False
Dynamic typing is the root of Python's polymorphism