1
I’m taking a look at Numpy’s arrays and saw that method copy
should make a deep copy array. When I create an array of strings or numerical values this seems to be true. However, when I create an array containing an instance of a class I created, the method copy
copies only the reference (Shallow copy). For example:
import numpy as np
class Teste:
def __init(self, var1, var2):
self.var1 = var1
self.var2 = var2
def __copy__(self):
return Teste(self.var1, self.var2)
t = Teste(20, 30)
arr1 = np.array([t])
arr2 = arr1.copy()
id(arr1[0) == id(arr2[0]) == id(t)
The comparison on the last line of code returns True
, which indicates that both arr1
how much arr2
keep the same reference for the object t
. My expectation was that the method copy
create a new object Teste
.
I get this behavior when I use the method deepcopy
module copy
. So I was wondering if I’m using the method copy
of the array correctly and if this is really the expected behavior of this method.
Thank you for your reply. I’m following Deitel’s book, Python for Programmers, and in section 7.12 it says that the ndarray.copy method does a deep copy of the array. Apparently the author gave a big slip. Again, thank you very much.
– Igor Ribeiro