您的位置:首页 > 编程语言 > Python开发

python常用模块介绍之二:copy模块

2016-09-28 15:11 537 查看


简介:

        
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]))<
4000
/p>

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]的类型和值一致,身份不一致。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: