【问题标题】:Copying a list of objects and retaining their properties in Python在 Python 中复制对象列表并保留其属性
【发布时间】:2020-06-24 14:36:36
【问题描述】:

有时我们不想改变。在下面的代码中,我原来的 Things 发生了变异,即使我复制了包含它们的列表。我并不感到惊讶,但我想知道如何存储我的原始对象属性,以便我可以将我的 things 列表恢复到最初创建时的状态。

class Thing:
    def __init__(self, x):
        self.x = x

    def __str__(self):
        return str(self.x)

things = [Thing(10), Thing(20)]
original_things = things.copy()

for thing in things:
    print(thing)
print("All change")
things[0].x = 30
things[1].x = 40
print("Back to the beginning?")
things = original_things
for thing in things:
    print(thing)

【问题讨论】:

标签: python list object mutation


【解决方案1】:

阅读文档,卢克!

Python documentation for lists 说:

列表。复制(x)

返回列表的浅表副本。相当于a[:]

因此,bar_list = foo_list.copy() 等价于bar_list = foo_list

根据@Gphilo,你想要的是copy.deepcopy

from copy import deepcopy
class Thing:
    def __init__(self, x):
        self.x = x

    def __str__(self):
        return str(self.x)

things = [Thing(10), Thing(20)]
original_things = deepcopy(things)

for thing in things:
    print(thing)
print("All change")
things[0].x = 30
things[1].x = 40
print("Back to the beginning!")
things = original_things
for thing in things:
    print(thing)

输出:

10
20
All change
Back to the beginning!
10
20

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-18
    • 2023-01-19
    • 2014-04-11
    • 2020-05-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多