As in the question, I wonder how (if I can) I can create an attribute that gives me the matrix size, but I want to do it with the property
decorator.
in this example, is it possible to use such a decorator?
class Matrix:
def __init__(self, m, n, init=True):
if init:
self.rows = [[0] * n for x in range(m)]
else:
self.rows = []
self.m = m
self.n = n
def __getitem__(self, idx):
return self.rows[idx]
def __setitem__(self, idx, item):
self.rows[idx] = item
I'm still exploring the syntax, and i'd like some advice on doing this.
What you want to do is very simple — textbook trivial — so it's unclear what "advice" you want. Stack Overflow is not intended to replace existing tutorials or documentation. See How much research effort is expected of Stack Overflow users?.
class Matrix:
def __init__(self, m, n, init=True):
if init:
self.rows = [[0] * n for x in range(m)]
else:
self.rows = []
self.m = m
self.n = n
def __getitem__(self, idx):
return self.rows[idx]
def __setitem__(self, idx, item):
self.rows[idx] = item
@property
def size(self):
return self.m * self.n
if __name__ == '__main__':
mat = Matrix(3, 3)
print(mat.size) # -> 9