有没有办法为类的实例定义[]运算符?

Mat*_*llo 2 python object operators

我想定义类来表示矩阵

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)
Run Code Online (Sandbox Code Playgroud)

其中mat是列表列表,以表示矩阵

A = | a b |
    | c d |
Run Code Online (Sandbox Code Playgroud)

我可以写下面的内容

A = matrix( [ [a, b], [c, d] ])
Run Code Online (Sandbox Code Playgroud)

我也开始定义一些运算符,比如

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
Run Code Online (Sandbox Code Playgroud)

现在,如果我想访问i, j矩阵中的元素,A我必须这样做

A.mat[i][j]
Run Code Online (Sandbox Code Playgroud)

问题是:我可以定义运算符[ ]吗?

A[i][j]
Run Code Online (Sandbox Code Playgroud)

就像我定义的那样__add__

ham*_*ene 7

operator []调用__getitem__:

class A:
    def __getitem__(self, index):
        return index+1

a = A()
print(a[1]) # prints 2
Run Code Online (Sandbox Code Playgroud)

您可以通过返回代表该行并且也响应的代理对象来实现[] [] __getitem__.或者,您可以接受元组作为索引并使用A[i,j]语法.