I have a class that store a numpy
array and the class has a method to modify the array
class A:
def __init__(self, matrix):
self.Matrix = matrix
def modify(self):
self.Matrix *= 2
obj = A(someMatrix)
Now here's the ridiculous part
p = obj.Matrix
obj.modify()
q = obj.Matrix
p - q # this is the 0 matrix !!!
So I realized p and q must be storing the same address (to obj.Matrix
) but this is clearly not what I am trying to do: I wanted to take the difference between the matrix before and after it's been updated!
Then I did this
p = np.array(obj.Matrix)
obj.modify()
q = np.array(obj.Matrix)
p - q # worked
But if I do
class A:
def __init__(self):
self.k = 1
def mod(self):
self.k *= 2
a = A()
p = a.k
a.mod()
q = a.k
print(p,q) # p = 1, q = 2
But how do I solve this problem in general: how do I store the value of the object variable/attribute rather than the address to the variable??
Thank you a ton!