'Every object's attribute update when I just want one
When making objects of a certain class, I give them a matrix as an attribute and store these objects in a different class, however when I change this matrix for one object, it changes for every object
import numpy as np
class A:
def __init__(self, matrix):
self.matrix = matrix
class B:
def __init__(self):
self.objects = []
matrix = np.matrix([
[0,0,0],
[0,0,0],
[0,0,0]
])
for i in range(10):
newObject = A(matrix)
self.objects.append(newObject)
objectB = B()
objectB.objects[0].matrix[0] = [1,1,1] # change top row of first object to 1,1,1
for object in objectB.objects:
print(object.matrix)
The code above prints 10 matrices all with [1,1,1] as the top row but should just print the first matrix with [1,1,1] on the top row and the other 9 matrices with all zeros
Solution 1:[1]
Simply use the copy function when creating the matrix attribute in class A
self.matrix = matrix.copy()
This makes a unique matrix for each object instead of referencing the same matrix.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
