在另一个属性上调用del时,对象的list属性会发生变化

Naz*_*oth 2 python list object del python-3.x

我对以下代码的行为感到困惑:

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)
Run Code Online (Sandbox Code Playgroud)

我认为应该出来的是:

[0,1,2,3,4,5]
[0,1,2,4,5]
Run Code Online (Sandbox Code Playgroud)

我得到的是这个:

[0,1,2,4,5]
[0,1,2,4,5]
Run Code Online (Sandbox Code Playgroud)

为什么第二个列表中的元素在未直接更改时会被删除?或者python是否以正常情况发生的方式处理属性?

那么我应该如何改变我得到我想要的代码呢?

hsp*_*her 6

Lists在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[::]
Run Code Online (Sandbox Code Playgroud)

注意:并非所有类型的对象都支持"深度复制".