【问题标题】:A deep copy of list of objects instantiates new objects?对象列表的深层副本实例化新对象?
【发布时间】:2018-01-09 17:06:41
【问题描述】:

首先,我编写了一个出于某些目的需要的类。我有这个类的几个对象,我把它们放在一个列表中。可能是这样的:

obj0=created_class(0)
obj1=created_class(1)
List_of_obj=[obj0,obj1]

现在我需要一份列表的深层副本:

Deep_copy=List_of_obj[:]

我的问题是:这会从创建的类中实例化新对象吗?

【问题讨论】:

  • 很容易发现:使用is 运算符来检查对象。但是是什么让你认为[:] 创建了一个deep 副本?

标签: python-3.x object deep-copy


【解决方案1】:

切片 ([:])不会创建列表的深层副本。

>>> class K:
...     def __init__(self, v):
...             self.v = v
...     def __repr__(self):
...             return f'<K: {self.v} ({id(self)})>'
... 
>>> l = [K(1), K(2)]
>>> l
[<K: 1 (4556562104)>, <K: 2 (4556562328)>]
>>> l[:]
[<K: 1 (4556562104)>, <K: 2 (4556562328)>]
>>> from copy import deepcopy
>>> deepcopy(l)
[<K: 1 (4556561880)>, <K: 2 (4556560480)>]

注意对象的 id 相同和不同的地方。

如果您的班级在抄写时需要特别注意,您可以通过documentation of the copy module in the standard lib了解更多信息。

【讨论】:

    猜你喜欢
    • 2013-04-09
    • 1970-01-01
    • 1970-01-01
    • 2016-02-15
    • 2015-12-28
    • 1970-01-01
    • 2011-12-09
    相关资源
    最近更新 更多