前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Python 强化训练:第六篇

Python 强化训练:第六篇

作者头像
谢伟
发布2018-06-06 12:01:24
3530
发布2018-06-06 12:01:24
举报
文章被收录于专栏:GopherCoderGopherCoder

强化训练:第六篇


1. 深浅拷贝:是否是同一个对象,使用id判断是否指向同一个对象, 深浅拷贝,引用区分可变对象和不可变对象
代码语言:javascript
复制
# 赋值法创建引用, 指向同一对象, id值相同

foo1 = 3
foo2 = foo1
print("id = ", id(foo1), "id = ", id(foo2))
#id =  1493167984 id =  1493167984

foo1 = 4
print(foo2, foo1)
#3 4
# 整型不可变对象, python 会缓存数据

foo3 = 3
foo4 = 2 + 1
print("id = ", id(foo3), "id = ", id(foo4))
#id =  1493167984 id =  1493167984


# python 仅缓存简单整型

foo5 = 3.14
foo6 = 2.14 + 1
foo7 = foo5
print("id = ", id(foo5), "id = ", id(foo6), "id = ", id(foo7))
#id =  3449480 id =  3449504 id =  3449480

# 可变对象, 引用, 浅拷贝影响源数据, 深拷贝指向不同对象

## 引用

list_one = [1, 2, 3]
list_two = list_one
print("id = ", id(list_one), "id = ", id(list_two))
# id =  12186120 id =  12186120
list_one[2] = 4
print(list_two)
#[1, 2, 4]

list_two[1] = 5
print(list_one)
print("id = ", id(list_one), "id = ", id(list_two))

#[1, 5, 4]
#id =  12186120 id =  12186120

## 深浅拷贝

from copy import copy, deepcopy

list_three = [1, 2, [3, 4]]
list_four = list_three    # 引用:指向相同对象
list_five = copy(list_three)    # 浅拷贝
list_six = deepcopy(list_three)    # 深拷贝
print(id(list_three), id(list_four), id(list_five), id(list_six))
#12185736 12185736 12321864 12127880

list_four[1] = 1156143589
print("list_three= ", list_three, "list_five= ", list_five, "list_six= ", list_six)
# list_three=  [1, 1156143589, [3, 4]] list_five=  [1, 2, [3, 4]] list_six=  [1, 2, [3, 4]]

list_three[0] = 88688
print("list_four= ", list_four, "list_five= ", list_five, "list_six= ", list_six)
#list_four=  [88688, 1156143589, [3, 4]] list_five=  [1, 2, [3, 4]] list_six=  [1, 2, [3, 4]]


list_five[0] = 4444
print("list_three= ", list_three, "list_four= ", list_four)
# list_three=  [88688, 1156143589, [3, 4]] list_four=  [88688, 1156143589, [3, 4]]

list_five[2][1] = 666666
print("list_three= ", list_three, "list_four= ", list_four, "list_six= ", list_six)
#list_three=  [88688, 1156143589, [3, 666666]] list_four=  [88688, 1156143589, [3, 666666]] list_six=  [1, 2, [3, 4]]

list_six[2][0] = 99999
print("list_three= ", list_three, "list_four= ", list_four, "list_five= ", list_five, "list_six= ", list_six)
#list_three=  [88688, 1156143589, [3, 666666]] list_four=  [88688, 1156143589, [3, 666666]] list_five=  [4444, 2, [3, 666666]] list_six=  [1, 2, [99999, 4]]

2. 总结

  1. 引用指向同一对象:相同id, 不可变对象独立操作,可变对象相互影响
  2. 浅拷贝:只拷贝父对象, 嵌套可变对象会影响数据源
  3. 深拷贝还会拷贝对象的内部的子对象:独立操作,不影响数据源
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2016.11.05 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 强化训练:第六篇
    • 2. 总结
    领券
    问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档