一个实例:
Python中对象的赋值都是进行对象引用(内存地址)传递,Python的运行就是创建内存空间,拷贝内存空间和删除内存空间的操作集合,浅复制和深复制之后得到对象的引用就是对象对一堆内存空间集合的引用!
Python中对象的赋值都是进行对象引用(内存地址)传递
作者:一二三是五六十
链接:http://www.imooc.com/article/19066?block_id=tuijian_wz
来源:慕课网
Python中对象的赋值都是进行对象引用(内存地址)传递
作者:一二三是五六十
链接:http://www.imooc.com/article/19066?block_id=tuijian
1、不可变数据类型:字符串、元组。
字符串的内存地址是唯一的,相等的元组的内存地址却不一定相等。
相等情况
import copy x = (1, 2) # type: Tuple[int, int] y = copy.copy(x) print(id(x)) print(id(y))
不相等情况
x = {'num1': 1, 'num2': (1, 2), 'num3': [1, (1, 2), 3]} y = x print(x) print(y) print(id(x)) print(id(y)) print(id(y['num3'])) print(id(x['num3'])) print(id(y['num2'])) print(id(x['num2'])) print(id(y['num3'][1])) print(id(x['num3'][1]))
2、浅复制和深复制
from copy import deepcopy x = {'num1': 1, 'num2': (1, 2), 'num3': [1, (1, 2), 3]} y = deepcopy(x) print(id(x)) print(id(y)) print(id(y['num1'])) print(id(x['num1'])) print(id(y['num3'])) print(id(x['num3'])) print(id(y['num3'][2])) print(id(x['num3'][2])) y = x.copy() print(id(x)) print(id(y)) print(id(y['num1'])) print(id(x['num1'])) print(id(y['num3'])) print(id(x['num3'])) print(id(y['num3'][2])) print(id(x['num3'][2]))