Python - What is the difference between shallow copy, deepcopy and normal assignment operation?

╰+攻爆jí腚メ 2022-05-29 07:47 344阅读 0赞

分享一个大牛的人工智能教程。零基础!通俗易懂!风趣幽默!希望你也加入到人工智能的队伍中来!请点击http://www.captainbed.net

Normal assignment operations will simply point the new variable towards the existing object. The docs explain the difference between shallow and deep copies:

The difference between shallow and deep copying is only relevant for compound objects (objects that contain other objects, like lists or class instances):

  • A shallow copy constructs a new compound object and then (to the extent possible) inserts references into it to the objects found in the original.
  • A deep copy constructs a new compound object and then, recursively, inserts copies into it of the objects found in the original.

Here’s a little demonstration:

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

Using normal assignment operatings to copy:

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

Using a shallow copy:

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

Using a deep copy:

  1. d = copy.deepcopy(c)
  2. print id(c) == id(d) # False - d is now a new object
  3. print id(c[0]) == id(d[0]) # False - d[0] is now a new object

发表评论

表情:
评论列表 (有 0 条评论,344人围观)

还没有评论,来说两句吧...

相关阅读