In addition to creating an auxiliary method that takes the operator as a parameter, as shown in the other answers, you can make use of other magic methods to simplify the logic of your class.
Consider the initial class:
class Matrix:
def __init__(self, matrix):
self.matrix = matrix
You can make your object eternal by defining the method __iter__
:
class Matrix:
def __init__(self, matrix):
self.matrix = matrix
def __iter__(self):
yield from iter(self.matrix)
This way, you can iterate over the matrix lines with the for
:
>>> m = Matrix([[1, 2, 3], [4, 5, 6]])
>>> for linha in m:
... print(linha)
[1, 2, 3]
[4, 5, 6]
You can use the method __len__
to return the dimension of the matrix:
class Matrix:
def __init__(self, matrix):
self.matrix = matrix
def __iter__(self):
yield from iter(self.matrix)
def __len__(self):
return len(self.matrix)
And so do:
>>> print(len(m))
2
You can implement the method __getitem__
to facilitate access to matrix lines:
class Matrix:
def __init__(self, matrix):
self.matrix = matrix
def __iter__(self):
yield from iter(self.matrix)
def __len__(self):
return len(self.matrix)
def __getitem__(self, key):
return self.matrix[key]
Can do:
>>> print(m[0])
[1, 2, 3]
Finally, implementing the addition and subtraction methods, your class could look like:
class Matrix:
def __init__(self, matrix):
self.matrix = matrix
@property
def size(self):
return (len(self), len(self[0]))
def __iter__(self):
yield from iter(self.matrix)
def __len__(self):
return len(self.matrix)
def __getitem__(self, key):
return self.matrix[key]
def __add__(self, other):
if self.size != other.size:
raise Exception('Matrizes de tamanhos diferentes')
return Matrix(
[
[self[i][j] + other[i][j] for j in range(len(self[i]))]
for i in range(len(self))
]
)
def __sub__(self, other):
if self.size != other.size:
raise Exception('Matrizes de tamanhos diferentes')
return Matrix(
[
[self[i][j] - other[i][j] for j in range(len(self[i]))]
for i in range(len(self))
]
)
Thanks for the reply, but I was already doing those things that you recommended me kk, still thank you!
– Matheus Andrade