python中的对象赋值(等号赋值、深复制、浅复制)
来源:互联网 发布:ubuntu搭建hadoop集群 编辑:程序博客网 时间:2024/06/06 01:00
代码:
import copyclass Obj(): def __init__(self,arg): self.x=argif __name__ == '__main__': obj1=Obj(1) obj2=Obj(2) obj3=Obj(3) obj4=Obj(4) lst=[obj1,obj2,obj3,obj4] lst1=lst lst2=copy.copy(lst) lst3=copy.deepcopy(lst) print(id(lst),id(lst1),id(lst2),id(lst3))输出:
(37271888, 37271888, 37688456, 37271816)从以上输出可以发现,通过等号直接赋值,只能使lst1获得lst的引用,lst1与lst共享同一份数据。而lst2和lst3都获得了自己的一份数据(list),lst2和lst3的区别见下面的代码:
print id(lst),'------>', for obj in lst: print id(obj), print '' print id(lst2),'------>', for obj in lst2: print id(obj), print '' print id(lst3),'------>', for obj in lst3: print id(obj),输出:
13887824 ------> 13888184 13939704 13938768 13941864 13960256 ------> 13888184 13939704 13938768 13941864 13887752 ------> 13960184 13960544 13960616 13960688从以上输出可以发现,lst、lst2、lst3对应的list各不相同,但lst和lst2包含的对象是相同的,也就是说,浅复制没有进行递归复制,仅复制了最外一层
官网对二者区别的描述:
The difference between shallow and deep copying is only relevant for compound objects (objects that contain other objects, like lists or class instances):
- A shallow copy constructs a new compound object and then (to the extent possible) inserts references into it to the objects found in the original.
- A deep copy constructs a new compound object and then, recursively, inserts copies into it of the objects found in the original.
0 0
- python中的对象赋值(等号赋值、深复制、浅复制)
- 深复制,浅复制,和对象赋值
- 对象赋值与复制
- Python中的赋值以及深复制和浅复制(深拷贝和浅拷贝)
- C++中的对象的赋值和复制
- C++中的对象的赋值和复制
- C++中的对象的赋值和复制
- 对象复制和对象赋值
- 对象用等号赋值
- 对象的赋值和复制
- javascript中等号赋值究竟是复制还是在等号两边建立了联系
- 对象复制和对象赋值的区别
- 对象复制和对象赋值的区别
- 对象的赋值与对象的复制
- 【c++语言基础】深复制与浅复制,深赋值与浅赋值
- IO对象不可复制和赋值
- 第十讲:对象的赋值和复制
- C++IO对象不可复制或赋值
- Leetcode 树 Balanced Binary Tree
- C#学习笔记-泛型
- Page.ClientScript.RegisterStartupScript
- 以为这是成长带给我们的
- 基于栈与基于寄存器的指令集架构
- python中的对象赋值(等号赋值、深复制、浅复制)
- HTML Color Code
- Cocos2d-x学习之windows 7 android环境搭建
- Python基础01(前期工作和安装python)
- splint选项介绍
- 深深庭院几许,袅袅烟雨情
- 电子罗盘数据的解析
- 查找一个字符串中出现次处最多的那个字符,并输出出现次数
- 配置两台电脑maven共用一个nexus私服