I created a class that has lots of numpy arrays inside. I created a __getitem__ function that attempts to return the class with the arrays indexed like so:
MyClass[i].array1 is equivalent to MyClass.array1[i]
I would like the _ _ getitem _ _ to return references, but they are returning copies, so that assignment doesn't work.
print(MyClass[i].array1)
returns 0
MyClass[i].array1 = 10
print(MyClass[i].array1)
still returns 0
This is the _get_item_ code I'm using:
def __getitem__(self, indices):
g = copy.copy(self) # should be a shallow copy?
for key,value in g.__dict__.iteritems():
g.__dict__[key] = value[indices]
return g
I've also tried:
def __getitem__(self, indices):
g = MyClass()
for key,value in self.__dict__.iteritems():
g.__dict__[key] = value[indices]
return g
and:
def __getitem__(self, indices):
g = MyClass()
g.__dict__ = self.__dict__
for key,value in g.__dict__.iteritems():
g.__dict__[key] = value[indices]
return g
Note, this last instance does indeed seem to return references, but not the way I want. If I index my class using this last code, it performs indexing and truncating on the arrays in the original class, so:
g = MyClass[i].array1 truncates and overwrites the original array in MyClass to only have elements of index i like so:
print(len(MyClass.array1))
returns 128
print(MyClass[0].array1)
returns 0
now MyClass.array1 is a single float value, obviously not what I wanted.
I hope this is clear enough, and any help would be appreciated.
I found this but I wasn't quite sure if this applied to my problem.