专栏首页GopherCoderPython 强化训练:第六篇

Python 强化训练:第六篇

强化训练:第六篇


1. 深浅拷贝:是否是同一个对象,使用id判断是否指向同一个对象, 深浅拷贝,引用区分可变对象和不可变对象

# 赋值法创建引用, 指向同一对象, 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. 深拷贝还会拷贝对象的内部的子对象:独立操作,不影响数据源

本文参与腾讯云自媒体分享计划,欢迎正在阅读的你也加入,一起分享。

我来说两句

0 条评论
登录 后参与评论

相关文章

  • Python程序员最常犯的10个错误,你中招了吗?

    大数据文摘
  • 手把手 | 数据科学速成课:给Python新手的实操指南

    大数据文摘
  • 亲测,手把手教你用Python抢票

    大数据文摘
  • 手把手:扫描图片又大又不清晰?这个Python小程序帮你搞定!

    大数据文摘
  • 手把手:自然语言处理太难?按这个套路走,就是砍瓜切菜!(附Python代码)

    大数据文摘
  • 网络流算法Dinic的Python实现

    forrestlin
  • python 超时任务kill

    YG
  • 网络流算法Push-relabel的Python实现

    forrestlin
  • Centos下安装python mysqldb

    forrestlin
  • Python3编码与mysql编码介绍

    YG

扫码关注云+社区

领取腾讯云代金券