我对以下代码的行为感到困惑:
data = [0,1,2,3,4,5]
class test():
def __init__(self,data):
self.data=data
self.data2=data
def main(self):
del self.data2[3]
test_var = test(data)
test_var.main()
print(test_var.data)
print(test_var.data2)
我认为应该出来的是:
[0,1,2,3,4,5]
[0,1,2,4,5]
我得到的是这个:
[0,1,2,4,5]
[0,1,2,4,5]
为什么第二个列表中的元素在未直接更改时被删除?或者 python 是否以这种正常发生的方式处理属性?
那么我应该如何更改我得到我想要的代码呢?
最佳答案
列表
在 Python 中是可变的并通过引用传递。每当您分配它或将其作为参数传递时,都会传递对它的引用而不是副本。因此你看到的结果。如果你真的想改变它,你需要对它进行深度复制。
import copy
class test():
def __init__(self, data):
self.data = copy.deepcopy(data)
self.data2 = copy.deepcopy(data2)
# if the list is going to be flat and just contain basic immutable types,
# slicing (or shallow-copy) would do the job just as well.
class test():
def __init__(self, data):
self.data = data[::] # or data[:] for that matter as @Joe Iddon suggested
self.data2 = data[::]
Note: not all types of objects support "deep-copying".
关于python - 在不同的属性上调用 del 时,对象的列表属性会发生变化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48049947/