python - 在不同的属性上调用 del 时,对象的列表属性会发生变化

标签 python python-3.x list object del

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

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/

相关文章:

python - 如何只向用户询问一次符号值而不是在每次迭代中?

python - 与 Mechanize submit() 方法等效的 urllib 代码是什么?

python-3.x - Python Pandas : groupby one column, 只在另外一列聚合,取对应数据

python - 在不使用 .join 的情况下在 input() 提示中打印列表的元素并将列表转换为 str

c# - 如何使用 linq 映射两个列表

python - 如何向 pandas 数据框添加二级索引

python - Django,使用自定义用户模型添加好友

python - 用python中的字符串列表替换一个字符串列表

python tkinter 通过单击按钮打开新窗口并关闭第一个窗口

python - 从包含键的列表创建字典的键