我正在尝试为我的类Matrix编写一个新的 add () - 方法,我正在实现它而不使用numpy。
使用我的add方法时出现以下问题:
@classmethod
def __add__(self, other):
print(self._data)
print(other.data)
row = len(self._data)
column = len(self._data[0])
addition = [[0 for c in range(column)] for r in range(row)]
for i in range(row):
for j in range(column):
addition[i][j] += self._data[i][j] + other[i][j]
return Matrix(addition)
打印为self和其他产生相同的值,尽管它不应该:
a = Matrix([[1, 2], [3, 4]])
b = Matrix.filled(2, 2, 1)
c = a + b
打印输出,清楚地显示c = b + b:
[[1, 1], [1, 1]]
[[1, 1], [1, 1]]
这是我为我的课程实现的其余代码:
class Matrix(object):
#initializes instance of Matrix
@classmethod
def __init__(self, iterable):
self._data = iterable
count = len(iterable[0])
for i in range(len(iterable)):
for j in range(len(iterable[i])):
assert count == len(iterable[i])
assert type(iterable[i][j]) == int or type(iterable[i][j]) == float
#get item at key - a[0,1] -> a[0][1]
@classmethod
def __getitem__(self, key):
if (isinstance(key,int)):
return self._data[key]
else:
return self._data[key[0]][key[1]]
#set value at key - a[1,0] = 42 -> a[1][0] = 42
@classmethod
def __setitem__(self, key, value):
if (isinstance(key,int)):
self._data[key] = value
else:
self._data[key[0]][key[1]] = value
@classmethod
def __str__(self):
k = "["
for i in self._data:
k = k + str(i)
k = k +"," + "\n" + " "
return k[:-3] + "]"
#builds matrix with dimensions row * column
@staticmethod
def filled(rows,cols, value):
matrix = [[value] * cols for i in range(rows)]
return Matrix(matrix)
#creates and returns copy of matrix
@property
def data(self):
matrix = copy.deepcopy(self._data)
return matrix
非常感谢你的时间和帮助