对于不可变对象,所有指向该对象的变量在内存中共用一个地址:
>>> a = 1
>>> b = 1
>>> c = a + 0
>>> print(id(a)==id(b) and id(a)==id(c))
True
不可变对象改变一个值,原始变量不变:
>>> a = 1
>>> b = a
>>> b = 2
>>> a
1
可变对象改变一个值,原始变量也被改变:
>>> a = [1]
>>> b = a
>>> b.append(2)
>>> a
[1, 2]
注:当对象的引用计数为0时,该对象对应的内存会被回收。
不可变对象无论深浅拷贝其地址都一样;
可变对象以list举例,分三种情况:
举例说明:
>>> import copy
>>> a = [1,2,[1,2]]
>>> b = a #直接赋值
>>> c = copy.copy(a) #浅拷贝
>>> d = a[:] #相当于浅拷贝
>>> e = copy.deepcopy(a) #深拷贝
>>> a.append(3)
>>> a
[1, 2, [1, 2], 3]
>>> b #直接赋值的跟随改变
[1, 2, [1, 2], 3]
>>> c #浅拷贝外围为拷贝,因此不变
[1, 2, [1, 2]]
>>> d #同c
[1, 2, [1, 2]]
>>> e #深拷贝内外都不变
[1, 2, [1, 2]]
>>> a[2].append(3)
>>> a
[1, 2, [1, 2, 3], 3]
>>> b #直接赋值的跟随改变
[1, 2, [1, 2, 3], 3]
>>> c #浅拷贝内部拷贝的是应用,跟随改变
[1, 2, [1, 2, 3]]
>>> d #同c
[1, 2, [1, 2, 3]]
>>> e #深拷贝内外都不变
[1, 2, [1, 2]]