8wDlpd.png
8wDFp9.png
8wDEOx.png
8wDMfH.png
8wDKte.png

浅拷贝、深拷贝和普通赋值操作有什么区别?

Dreamify App 2月前

92 0

导入 copya = \'deepak\'b = 1, 2, 3, 4c = [1, 2, 3, 4]d = {1: 10, 2: 20, 3: 30}a1 = copy.copy(a)b1 = copy.copy(b)c1 = copy.copy(c)d1 = copy.copy(d) print(\'immutable - id(a)==id(a1)\', id(a...

import copy

a = "deepak"
b = 1, 2, 3, 4
c = [1, 2, 3, 4]
d = {1: 10, 2: 20, 3: 30}

a1 = copy.copy(a)
b1 = copy.copy(b)
c1 = copy.copy(c)
d1 = copy.copy(d)


print("immutable - id(a)==id(a1)", id(a) == id(a1))
print("immutable - id(b)==id(b1)", id(b) == id(b1))
print("mutable - id(c)==id(c1)", id(c) == id(c1))
print("mutable - id(d)==id(d1)", id(d) == id(d1))

我得到以下结果:

immutable - id(a)==id(a1) True
immutable - id(b)==id(b1) True
mutable - id(c)==id(c1) False
mutable - id(d)==id(d1) False

如果我执行深度复制:

a1 = copy.deepcopy(a)
b1 = copy.deepcopy(b)
c1 = copy.deepcopy(c)
d1 = copy.deepcopy(d)

结果是一样的:

immutable - id(a)==id(a1) True
immutable - id(b)==id(b1) True
mutable - id(c)==id(c1) False
mutable - id(d)==id(d1) False

如果我进行赋值操作:

a1 = a
b1 = b
c1 = c
d1 = d

结果是:

immutable - id(a)==id(a1) True
immutable - id(b)==id(b1) True
mutable - id(c)==id(c1) True
mutable - id(d)==id(d1) True

有人能解释一下这些副本之间到底有什么区别吗?这和可变和不可变对象有关吗?如果是的话,你能给我解释一下吗?

帖子版权声明 1、本帖标题:浅拷贝、深拷贝和普通赋值操作有什么区别?
    本站网址:http://xjnalaquan.com/
2、本网站的资源部分来源于网络,如有侵权,请联系站长进行删除处理。
3、会员发帖仅代表会员个人观点,并不代表本站赞同其观点和对其真实性负责。
4、本站一律禁止以任何方式发布或转载任何违法的相关信息,访客发现请向站长举报
5、站长邮箱:yeweds@126.com 除非注明,本帖由Dreamify App在本站《dictionary》版块原创发布, 转载请注明出处!
最新回复 (0)
  • 正常的赋值操作只会将新变量指向现有对象。 docs 解释了浅拷贝和深拷贝之间的区别:

    浅复制和深复制之间的区别仅与复合对象(包含其他对象的对象,如列表或类实例)有关:

    • p2

    • p3

    以下是一个小演示:

    import copy
    
    a = [1, 2, 3]
    b = [4, 5, 6]
    c = [a, b]
    

    使用正常赋值操作来复制:

    d = c
    
    print id(c) == id(d)          # True - d is the same object as c
    print id(c[0]) == id(d[0])    # True - d[0] is the same object as c[0]
    

    使用浅拷贝:

    d = copy.copy(c)
    
    print id(c) == id(d)          # False - d is now a new object
    print id(c[0]) == id(d[0])    # True - d[0] is the same object as c[0]
    

    使用深层复制:

    d = copy.deepcopy(c)
    
    print id(c) == id(d)          # False - d is now a new object
    print id(c[0]) == id(d[0])    # False - d[0] is now a new object
    
返回
作者最近主题: