首页 > 解决方案 > 为什么python删除影响类实例的函数

问题描述

我正在使用以下输出运行此代码,但我不希望 .remove() 影响类实例。

class dumby:
    def __init__(self):
        a = []


test1 = dumby()
A = [1,1]
test1.a = A
print(test1.a)
A.remove(A[0])
print(test1.a)

输出

[1, 1]
[1]

我想要的输出是

[1, 1]
[1, 1]

请帮忙!

标签: pythonlistclass

解决方案


Python 变量(或成员属性)实际上包含对对象的引用。一些对象是不可变的(数字、字符串),但大多数特别是列表。因此,当您修改可变对象时,对它的所有引用都会受到影响,无论使用什么引用来更改它。

这正是这里发生的事情:

test1 = dumby()  # ok, you create a new dumby
A = [1,1]        # ok you create a new list referenced by A
test1.a = A      # test1.a now references the same list
print(test1.a)
A.remove(A[0])   # the list is modified
print(test1.a)   # you can control that the list is modified through the other ref.

您要做的是分配原始列表的副本:

test1.a = A[:]   # test1.a receives a copy of A (an independent object)

推荐阅读