I want to define class to represent a matrix
class matrix:
def __init__(self, mat):
self.mat = mat
self.dim = len(mat)
@classmethod
def withDim(matrix, dimension):
mat = [ [0]*dimension for i in range(dimension)]
return matrix(mat)
where mat is a list of lists, so to represent the matrix
A = | a b |
| c d |
I can write the following
A = matrix( [ [a, b], [c, d] ])
I’ve also started to define some operators, like
def __add__(self, other):
n = self.dim
result = self.withDim(n)
for i in range(n):
for j in range(n):
result.mat[i][j] = self.mat[i][j] + other.mat[i][j]
return result
Now if I want to access element i, j in matrix A I have to do
A.mat[i][j]
The question is: can I define the operator [ ] in order to do
A[i][j]
just like I defined __add__?
operator[] calls
__getitem__:You can implement [][] by returning a proxy object which represents the row and also responds to
__getitem__. Or, you can accept tuple as index and useA[i,j]syntax.