python - How to implement interface for submatrix like m[1:3, 0:2] += 1? -
i asked question still can't figure out how implement this.
i have matrix class:
class matrix(list): def __getitem__(self, item): try: return list.__getitem__(self, item) except typeerror: rows, cols = item return [row[cols] row in self[rows]]
it allows things this:
m = matrix([[i+j j in [0,1,2,3]] in [0,4,8,12]]) print(m[0:2, 0:2]) print: [[0, 1], [4, 5]]
i want able add/multiply submatrix elements given value, like:
m[0:2, 0:2] += 1 print(m[0:2, 0:2]) should print: [[1, 2], [5, 6]]
i'm trying implement methods: __add__
, __setitem__
def __setitem__(self, key, value): print(key, value) def __add__(self, item): print(item) in range(self): j in range(self[0]): self[i][j] += item
at least want see print something. doesn't happen. i'm trying such example:
m[1:2, 2:3] = m[1:2, 2:3] + 1
and error like: typeerror: can concatenate list (not "int") list
.
so, i'm not @ magic methods. call fails before. how this?
you have return matrix object "getitem"
class matrix(list): def __getitem__(self, item): print "get" try: return matrix(list.__getitem__(self, item)) except typeerror: rows, cols = item return matrix([row[cols] row in self[rows]]) def __setitem__(self, key, value): print(key, value) def __add__(self, item): print "messi great" print(item) # in range(self): # j in range(self[0]): # self[i][j] += item m = matrix([[i+j j in [0,1,2,3]] in [0,4,8,12]]) print m[1:2, 2:3] m[1:2, 2:3] = m[1:2, 2:3] + 1
Comments
Post a Comment