zoukankan      html  css  js  c++  java
  • python开发_copy(浅拷贝|深拷贝)_博主推荐

    python中,有着深拷贝和浅拷贝,即copy模块

    下面我们就来聊一下:

    运行效果:

    ==================================================

    代码部分:

    ==================================================

     1 #python copy
     2 '''
     3 个人认为:
     4     浅拷贝:拷贝后,对象的引用没有发生变化,而对象的行为发生变化,会反映到拷贝后的对象身上
     5     深拷贝:拷贝后,对象的引用发生了变化,即对象不同,所以,即使对象再怎么变,也不会对其他对象产生影响
     6 '''
     7 
     8 import copy
     9 
    10 def shallow_copy(s):
    11     '''make a shallow copy of s.'''
    12     return copy.copy(s)
    13 
    14 def deep_copy(d):
    15     '''make a deep copy of d.'''
    16     return copy.deepcopy(d)
    17 
    18 def test_shallow():
    19     tem_data = ['a', 'c', 'e', 't', [1, 2, 3]]
    20     print('被拷贝的源数据为:{}'.format(tem_data))
    21     s_copy = shallow_copy(tem_data)
    22     print('进行浅拷贝....')
    23     tem_data.append('Hongten')
    24     tem_data[4].append('4')
    25     print('修改源数据后:{}'.format(tem_data))
    26     print('拷贝后的数据为:{}'.format(s_copy))
    27 
    28 def test_deep():
    29     tem_data = ['a', 'c', 'e', 't', [1, 2, 3]]
    30     print('被拷贝的源数据为:{}'.format(tem_data))
    31     s_copy = deep_copy(tem_data)
    32     print('进行深拷贝....')
    33     tem_data.append('Hongten')
    34     tem_data[4].append('4')
    35     print('修改源数据后:{}'.format(tem_data))
    36     print('拷贝后的数据为:{}'.format(s_copy))
    37 
    38 def test_s_copy():
    39     '''listB复制了listA,这时候listB是对listA的一个引用
    40     他们指向的是同一个对象:[1, 2, 3, 4, 5],当我们试图修
    41     改listB[1] = 'Hongten'的时候,listB的所指向的对象的
    42     行为发生了变化,即元素的值发生了变化,但是他们的引用是没
    43     有变化的,所以listA[1] = 'Hongten'也是情理之中的事'''
    44     listA = [1, 2, 3, 4, 5]
    45     listB = listA
    46     listB[1] = 'Hongten'
    47     print('listA = {}, listB = {}'.format(listA, listB))
    48 
    49 def test_clone():
    50     '''进行了列表的克隆操作,即拷贝了另一个列表,这样的操作,
    51     会创造出新的一个列表对象,使得listA和listB指向不同的对象,
    52     就有着不同的引用,所以当listB[1] = 'Hongten'的时候,
    53     listA[1]还是等于2,即不变'''
    54     listA = [1, 2, 3, 4, 5]
    55     listB = listA[:]
    56     listB[1] = 'Hongten'
    57     print('listA = {}, listB = {}'.format(listA, listB))
    58 
    59 def main():
    60     print('浅拷贝Demo')
    61     test_shallow()
    62     print('#' * 50)
    63     print('深拷贝Demo')
    64     test_deep()
    65     print('#' * 50)
    66     test_s_copy()
    67     print('#' * 50)
    68     test_clone()
    69 
    70 if __name__ == '__main__':
    71     main()
  • 相关阅读:
    SpringBoot 如何生成接口文档,老鸟们都这么玩的!
    ELK 外网访问
    Elasticsearch 7.x配置用户名密码访问 开启x-pack验证
    在centos7 中安装Kibana
    在centos7 安装Elasticsearch 步骤:
    cuda-pytorch-gpu快速配置
    Face 2 to 3 D
    PointNet++
    PointNet:Deep Learning on Point Sets for 3D Classification and Segmentation
    3D Face Modeling From Diverse Raw Scan Data
  • 原文地址:https://www.cnblogs.com/hongten/p/hongten_python_copy.html
Copyright © 2011-2022 走看看