python常用模块介绍之二:copy模块
来源:互联网 发布:什么是网络信息检索 编辑:程序博客网 时间:2024/05/01 05:06
简介:
copy模块主要用于复制对象,有浅copy和深copy之分。
首先得清楚的理解《对象》的概念
对象:
python万物皆是对象。
对象分为可变和不可变2类,可变对象如:list,dict等;不可变对象如:基础类型,元组等。
对象有三大特性分别为:身份(id(a)),类型(type(a)),值(a)。
浅copy:
对象是不可变对象时:拷贝对象和原对象的三大特性一致
对象是可变对象时:拷贝对象和原对象的三大特性一致
深copy:
对象是不可变对象时:拷贝对象和原对象的三大特性一致
对象是可变对象时:拷贝的对象和原对象的类型和值一致,身份不一致
具体如下:
浅copy
import copy
x = 1
y = [11]
a = [x, y]
b = copy.copy(a)
print 'a[0] = %s and b[0] = %s' % (a[0], b[0])
print 'type(a[0]) = %s and type(b[0]) = %s' % (type(a[0]),type(b[0]))
print 'id(a[0]) = %s and id(b[0]) = %s' % (id(a[0]),id(b[0]))
print '*********************'
print 'a[1] = %s and b[1] = %s' % (a[1], b[1])
print 'type(a[1]) = %s and type(b[1]) = %s' %(type(a[1]), type(b[1]))
print 'id(a[1]) = %s and id(b[1]) = %s' % (id(a[1]),id(b[1]))
结果:
a[0] = 1 and b[0] = 1
type(a[0]) = <type 'int'> and type(b[0]) = <type 'int'>
id(a[0]) = 31817608 and id(b[0]) = 31817608
*********************
a[1] = [11] and b[1] = [11]
type(a[1]) = <type 'list'> and type(b[1]) = <type 'list'>
id(a[1]) = 36362440 and id(b[1]) = 36362440
通过结果发现,a和b的三大特性完全一致。
深copy
import copy
x = 1
y = [11]
a = [x, y]
b = copy.deepcopy(a)
print 'a[0] = %s and b[0] = %s' % (a[0], b[0])
print 'type(a[0]) = %s and type(b[0]) = %s' %(type(a[0]), type(b[0]))
print 'id(a[0]) = %s and id(b[0]) = %s' % (id(a[0]),id(b[0]))
print '*********************'
print 'a[1] = %s and b[1] = %s' % (a[1], b[1])
print 'type(a[1]) = %s and type(b[1]) = %s' %(type(a[1]), type(b[1]))
print 'id(a[1]) = %s and id(b[1]) = %s' % (id(a[1]),id(b[1]))
结果:
a[0] = 1 and b[0] = 1
type(a[0]) = <type 'int'> and type(b[0]) = <type 'int'>
id(a[0]) = 31555464 and id(b[0]) = 31555464
*********************
a[1] = [11] and b[1] = [11]
type(a[1]) = <type 'list'> and type(b[1]) = <type 'list'>
id(a[1]) =36624584 and id(b[1]) =36635656
通过结果发现,a[0]和b[0]的三大特性完全一致,a[1]和b[1]的类型和值一致,身份不一致。
- python常用模块介绍之二:copy模块
- python常用模块介绍
- python 常用模块介绍
- Python常用模块介绍
- Python常用模块介绍
- python常用模块介绍
- Python 常用模块介绍
- python 常用模块介绍
- python模块 - copy模块
- python模块系列之 - copy
- python常用模块介绍之三:logging模块
- python常用模块介绍之四:getopt模块
- python 之常用模块
- python常用模块介绍之一:string模块
- python之模块二
- python小模块-----copy 模块
- python常用模块之os模块
- python常用模块之time模块
- java常用数据结构的转换,不定期更新
- python处理mysql中文数据
- cookie ,session 和localStorage的区别详解
- Javascript闭包的几种写法及用途
- virtualenv+virtualenvwrapper+uwsgi+django配置
- python常用模块介绍之二:copy模块
- 函数声明与函数表达式的区别
- OpenMP并行程序设计-1e9求和(顺手存代码)
- [Android实践]之:Android官方提供的支持不同屏幕大小的全部方法
- 洛谷 P2014 选课
- Countries
- 读取同一个文件夹的统一格式的文件
- 亿级Web系统搭建——单机到分布式集群
- 读取XML(Java)