python - Avoid class initialization modified in method in python
问题描述
My code is below:
import numpy as np
class xx():
def __init__(self, x):
self.x = x
def main(self):
for i in [0,1,2,3]:
y = self.x
y[0, i] = 0
print(y)
z = np.array([[0.5,0.6,0.7,0.8],[1,2,3,4],[6,4,3,1]])
xx(z).main()
My original code is far more complicated than this, so I decided to create a similar example on the issue.
I meant to only change y in the for loop, and reassign y with self.x. but it seemed that self.x was changed in the for loop too. How can I avoid self.x getting modified each time as y changes?
解决方案
I would recommend using copy.deepcopy()
import copy
class xx():
def __init__(self, x):
self.x = x
def main(self):
for i in [0,1,2]:
y = copy.deepcopy(self.x)
y[0, i] = 0
print(y)
z = np.array([[1,1,1],[2,2,2]])
xx(z).main()
>>>[[0 1 1]
[2 2 2]]
>>>[[1 0 1]
[2 2 2]]
>>>[[1 1 0]
[2 2 2]]
推荐阅读
- android - Android 为什么按钮不适合屏幕
- python - 数据帧的熊猫切片与csv的不同编码不一致
- android - Android NDK ImageDecoder 函数需要构建错误
- r - 在R中的条件后添加填充行
- git - 如何在合并请求上应用 gitlab CI 中的 if else 条件?
- javascript - Javascript 解析 URI(GEO.IPIFY.ORG)
- amazon-web-services - 由于解析 URL 弃用,AWS EB 实例无法部署
- jquery - 将 jQuery 变量添加到输入字段的占位符中
- powershell - 在 Powershell 中阅读时
- python - 使用 Pandas 的每个职业的男女比例是多少