即使仅应用于其中一个实例,方法也会更改这两个实例

问题描述 投票:1回答:1

我很难理解为什么我的简单代码表现得像这样。我创建了2个实例a和b,它接受一个数组作为参数。然后我定义了一个方法来更改其中一个实例数组,但后来都改变了。知道为什么会这样,我怎么能避免改变其他实例的方法呢?

import numpy as np
class Test:
  def __init__(self, arg):
    self.arg=arg


  def change(self,i,j,new):
    self.arg[i][j]=new




array=np.array([[11,12,13]])
a=Test(array)
b=Test(array)
#prints the same as expected
print(a.arg)
print(b.arg)
print()
a.change(0,0,3)
#still prints the same, even though I did 
#not change b.arg
print(a.arg)
print(b.arg)
python python-3.x class numpy methods
1个回答
© www.soinside.com 2019 - 2024. All rights reserved.