为什么python会删除影响类instan的函数

2024-09-29 20:27:33 发布

您现在位置: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]

请帮帮我!你知道吗


Tags: 实例代码selfinitdefremoveclassprint
1条回答
网友
1楼 · 发布于 2024-09-29 20:27:33

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)

相关问题 更多 >

    热门问题