避免在 python 中的方法中修改 class 初始化
Avoid class initialization modified in method in python
我的代码如下:
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()
我的原始代码比这复杂得多,所以我决定在这个问题上创建一个类似的例子。
我的意思是只在 for 循环中更改 y,然后用 self.x 重新分配 y。但似乎 self.x 在 for 循环中也发生了变化。如何避免 self.x 每次随着 y 的变化而被修改?
我建议使用 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]]
我的代码如下:
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()
我的原始代码比这复杂得多,所以我决定在这个问题上创建一个类似的例子。
我的意思是只在 for 循环中更改 y,然后用 self.x 重新分配 y。但似乎 self.x 在 for 循环中也发生了变化。如何避免 self.x 每次随着 y 的变化而被修改?
我建议使用 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]]