如何实现子矩阵的接口,如m [1:3,0:2] + = 1?

时间:2016-05-25 05:25:53

标签: python matrix

我已经问过这个question,但仍然无法弄清楚如何实现这一点。

我有矩阵类:

class Matrix(list):
    def __getitem__(self, item):
        try:
            return list.__getitem__(self, item)
        except TypeError:
            rows, cols = item
            return [row[cols] for row in self[rows]]

它可以做这样的事情:

m = Matrix([[i+j for j in [0,1,2,3]] for i in [0,4,8,12]])
print(m[0:2, 0:2])
will print: [[0, 1], [4, 5]]

我还希望能够按给定值添加/乘以所有子矩阵元素,例如:

m[0:2, 0:2] += 1
print(m[0:2, 0:2])
should print: [[1, 2], [5, 6]]

我正在尝试实施这些方法:__add____setitem__

def __setitem__(self, key, value):
    print(key, value)

def __add__(self, item):
    print(item)
    for i in range(self):
        for j in range(self[0]):
            self[i][j] += item

至少我想看到他们打印出来的东西。但它不会发生。我正在尝试这样的例子:

m[1:2, 2:3] = m[1:2, 2:3] + 1

并收到如下错误:TypeError: can only concatenate list (not "int") to list

所以,我甚至不是魔术方法。之前通话失败。怎么做?

1 个答案:

答案 0 :(得分:1)

您必须从" getitem "

返回Matrix对象
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] for row in self[rows]])
    def __setitem__(self, key, value):
        print(key, value)

    def __add__(self, item):
        print "messi the great"
        print(item)
        # for i in range(self):
        #     for j in range(self[0]):
        #         self[i][j] += item
m = Matrix([[i+j for j in [0,1,2,3]] for i in [0,4,8,12]])
print m[1:2, 2:3]
m[1:2, 2:3] = m[1:2, 2:3] + 1