【发布时间】: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)
【问题讨论】:
-
这能回答你的问题吗? How to deep copy a list?
-
当需要不可变时也使用元组
标签: python list object mutation