0

I have a class where I defined a numpy array and then I created a copy of an object of that class:

import numpy as np
import copy as cp

class Test():
    x=5
    arr=np.array([5,3])

TEST_1=Test()
TEST_2=cp.copy(TEST_1)

If I change the value of x for TEST_1 it's ok, it doesn't affect TEST_2:

print(TEST_2.x)
TEST_1.x+=1
print(TEST_2.x)

>>>5

>>>5

But if I try to change the array of TEST_1 it also changes the array of TEST_2:

print(TEST_2.arr)
TEST_1.arr+=np.array([1,1])
print(TEST_2.arr)

>>>[5 3]

>>>[6 4]

I know it's because I have to create a copy of the array, but I don't know how to tell Python to do it when the array it's inside a class.

Thank you and sorry for the bad English.

Lory1502
  • 21
  • 3
  • 1
    You can add `__copy__` and `__deepcopy__` methods to your class: https://stackoverflow.com/questions/1500718/how-to-override-the-copy-deepcopy-operations-for-a-python-object – slothrop May 13 '23 at 10:28

1 Answers1

1

Ok I managed to solve it, I do this:

class Test():
def __init__(self):
    self.arr=np.array([5,3])
    self.x=5
    
def __deepcopy__(self, memo):
    cls = self.__class__
    result = cls.__new__(cls)
    memo[id(self)] = result
    for k, v in self.__dict__.items():
        setattr(result, k, cp.deepcopy(v, memo))
    return result

And now the array of the copy doesn't change

Lory1502
  • 21
  • 3