I want to create a custom array object. One of the functions I want to implement is the possibility to add two arrays of different lengths, more or less like so
[1, 2, 3] + [4, 5] = [5, 7, 3]
My custom class is defined like so
class MyArray:
def __init__(self, values):
self.values = values
def __len__(self):
return len(self.values)
def __getitem__(self, key):
"""Makes MyArray sliceable"""
if isinstance(key, slice):
return self.values[key.start:key.stop:key.step]
else:
return self.values[key]
def __add__(self, other):
""""Make addition of two MyArrays of different lengths possible."""
if len(self) >= len(other):
a = self
b = other
else:
a = other
b = self
a[:len(b)] += b[:]
return MyArray(a)
Something is missing however. There is something about the implementation of the slicing I guess.
import numpy as np
a = MyArray(np.array([1,2,3]))
b = MyArray(np.array([4,5]))
Direct assignment fails
a[2] = 3
Traceback (most recent call last):
File "<ipython-input-8-17351fe6de12>", line 1, in <module>
a[2] = 3
TypeError: 'MyArray' object does not support item assignment
And, obviously since direct assignment fails, my __add__
method fails.
c = a + b
File "<ipython-input-1-2ce5425b4430>", line 28, in __add__
a[:len(b)] += b[:]
TypeError: 'MyArray' object does not support item assignment
I also fixed some issues in your __getitem__
and __add__
functions (comments in code added) in addition to my comment , so will post as an answer:
class MyArray:
def __init__(self, values):
self.values = values
def __len__(self):
return len(self.values)
def __getitem__(self, key):
"""Makes MyArray sliceable"""
return self.values[key] # you don't need to check for slice, it is supported by default
def __add__(self, other):
""""Make addition of two MyArrays of different lengths possible."""
if len(self) >= len(other):
a = self
b = other
else:
a = other
b = self
a = MyArray(a.values) # you need to make a copy before addition
a[:len(b)] += b[:]
return a
def __setitem__(self, key, value):
self.values[key] = value
import numpy as np
a = MyArray(np.array([1,2,3]))
b = MyArray(np.array([4,5]))
a[2] = 4
c = a + b
print(c.values) # [5 7 4]
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.