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

 

通过结果发现,ab的三大特性完全一致。

 

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]的类型和值一致,身份不一致。

0 0