Python 强化训练:第六篇

作者: 谢小路 | 来源:发表于2016-11-05 11:48 被阅读128次

    强化训练:第六篇


    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. 深拷贝还会拷贝对象的内部的子对象:独立操作,不影响数据源

    相关文章

      网友评论

        本文标题:Python 强化训练:第六篇

        本文链接:https://www.haomeiwen.com/subject/zbtguttx.html