我想创建一个自定义数组对象。我要实现的功能之一是可以添加两个不同长度的数组,或多或少像这样
[1, 2, 3] + [4, 5] = [5, 7, 3]
我的自定义类的定义如下
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)
但是,缺少某些东西。我猜切片的实现有些事情。
import numpy as np
a = MyArray(np.array([1,2,3]))
b = MyArray(np.array([4,5]))
直接分配失败
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
显然,由于直接分配失败,所以我的__add__
方法失败了。
c = a + b
File "<ipython-input-1-2ce5425b4430>", line 28, in __add__
a[:len(b)] += b[:]
TypeError: 'MyArray' object does not support item assignment
答案 0 :(得分:1)
除了my comment外,我还修复了您的__getitem__
和__add__
函数(添加了代码注释)中的一些问题,因此将作为答案发布:
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]