Python的对象分为两种:可变(List,Dict)和不可变对象(String, Truple)
对于对Python对象和变量的理解:图解Python变量与赋值
修改可变对象不需要开辟新的内存地址,修改不可变对象需要开辟新的内存地址
拷贝问题对于可变对象和不可变对象来说是不一样的。
可变对象:浅拷贝和深拷贝完全复制了对象的内存地址
不可变对象:浅拷贝完全复制了对象的内存地址,而深拷贝则是复制了对象本身,并且重新开辟内存空间
代码示例:
>>> import copy
>>> a = ["hello", [1,2,3,4]]
>>> b = a
>>> c = copy.copy(a)
>>> d = copy.deepcopy(a)
>>> [id(x) for x in a]
[54182720, 54020488]
>>> [id(x) for x in b]
[54182720, 54020488]
>>> [id(x) for x in c]
[54182720, 54020488]
>>> [id(x) for x in d]
[54182720, 54018440]
>>> a[0] = "world"
>>> a[1].append(5)
>>> [id(x) for x in a]
[54182832, 54020488]
>>> [id(x) for x in b]
[54182832, 54020488]
>>> [id(x) for x in c]
[54182720, 54020488]
>>> [id(x) for x in d]
[54182720, 54018440]
>>> print(a)
['world', [1, 2, 3, 4, 5]]
>>> print(b)
['world', [1, 2, 3, 4, 5]]
>>> print(c)
['hello', [1, 2, 3, 4, 5]]
>>> print(d)
['hello', [1, 2, 3, 4]]