Python自定义类索引

eri*_*nla 2 python indexing

是否可以在python中创建一个可以用方括号索引但不能从其他索引类型派生的类?

我对制作带有可选索引的类感兴趣,它的行为如下:

class indexed_array():
    def __init__(self, values):
        self.values = values

    def __sqb__(self, indices):   #This is a made up thing that would convert square brackets to a function
        if len(indices) == 2:
            return self.values[indices[0]][indices[1]]
        elif len(indices) == 1:
            return self.values[indices[0]][0]

myarray = indexed_array([[1,2,3], [4,5,6], [7,8,9]])
print myarray[1, 1]     # returns 5
print myarray[1]        # returns 4
Run Code Online (Sandbox Code Playgroud)

有没有像我这样的真正方法__sqb__?或者,您可以用另一种方式索引自定义类吗?

don*_*mus 7

您需要实施__getitem__。请注意,单个索引将作为自身传递,而多个索引将作为元组传递

通常,您可以选择以以下方式处理此问题:

class indexed_array:
    def __getitem__(self, indices):
        # convert a simple index x[y] to a tuple for consistency
        if not isinstance(indices, tuple):
            indices = tuple(indices)

        # now handle the different dimensional cases
        ...
Run Code Online (Sandbox Code Playgroud)