python - 为什么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]
请帮忙!
解决方案
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)
推荐阅读
- android - How to solve Android ANR on in app billing?
- python - TypeError: __init__() got an unexpected keyword argument iam_api_key
- python - python openpyxl insert_cols 更改合并单元格和样式
- python - 如何附加一个包含子列表的列表?
- typescript - 打字稿:隐式调用带有注入参数的构造函数
- javascript - 如何在双击时追加和删除 div
- python - 更改熊猫列中的类别?
- java - PI - 从 python 代码中读取 java 中的数据
- c# - AWS 开发工具包 .NET DynamoDB ASYNC
- javascript - 如何将 calendar.google.com 嵌入到没有 API 的站点中