自定义数组。在MyArray.py文件中,定义了一个数组类,重写了一部分特殊方法以支持数组之间、数组与整数之间的四则运算以及内积、大小比较、成员测试和元素访问等运算符。 用python
时间: 2023-06-06 15:07:05 浏览: 170
可以这样实现:
```
class MyArray:
def __init__(self, arr):
self.arr = arr
def __add__(self, other):
temp_arr = []
if isinstance(other, MyArray):
for i in range(len(self.arr)):
temp_arr.append(self.arr[i] + other.arr[i])
elif isinstance(other, int):
for i in range(len(self.arr)):
temp_arr.append(self.arr[i] + other)
else:
raise TypeError("unsupported operand type(s) for +: 'MyArray' and '{}'".format(type(other)))
return MyArray(temp_arr)
def __sub__(self, other):
temp_arr = []
if isinstance(other, MyArray):
for i in range(len(self.arr)):
temp_arr.append(self.arr[i] - other.arr[i])
elif isinstance(other, int):
for i in range(len(self.arr)):
temp_arr.append(self.arr[i] - other)
else:
raise TypeError("unsupported operand type(s) for -: 'MyArray' and '{}'".format(type(other)))
return MyArray(temp_arr)
def __mul__(self, other):
temp_arr = []
if isinstance(other, MyArray):
for i in range(len(self.arr)):
temp_arr.append(self.arr[i] * other.arr[i])
elif isinstance(other, int):
for i in range(len(self.arr)):
temp_arr.append(self.arr[i] * other)
else:
raise TypeError("unsupported operand type(s) for *: 'MyArray' and '{}'".format(type(other)))
return MyArray(temp_arr)
def __matmul__(self, other):
if not isinstance(other, MyArray):
raise TypeError("unsupported operand type(s) for @: 'MyArray' and '{}'".format(type(other)))
if len(self.arr) != len(other.arr):
raise ValueError("matmul: Input operand shapes do not match")
result = 0
for i in range(len(self.arr)):
result += self.arr[i] * other.arr[i]
return result
def __lt__(self, other):
if not isinstance(other, MyArray):
raise TypeError("unorderable types: MyArray() < {}()".format(type(other)))
if len(self.arr) != len(other.arr):
raise ValueError("comparison of arrays with different lengths is not supported")
for i in range(len(self.arr)):
if self.arr[i] >= other.arr[i]:
return False
return True
def __contains__(self, item):
for i in range(len(self.arr)):
if self.arr[i] == item:
return True
return False
def __getitem__(self, index):
return self.arr[index]
def __str__(self):
return str(self.arr)
```
这里重写的特殊方法包括 `__add__`、`__sub__`、`__mul__`、`__matmul__`、`__lt__`、`__contains__` 和 `__getitem__`,分别表示加法、减法、乘法、内积、大小比较、成员测试和元素访问等运算符。其中,`__matmul__` 表示矩阵乘法运算符 `@`,而 `__lt__` 表示小于号 `<`。`__str__` 方法则用于将数组对象转换成字符串表示。
阅读全文