列表类列表

coo*_*490 2 python inheritance

我想创建自己的List of Lists类.当其中一个索引为负时,我希望它抛出一个列表索引超出范围错误.

class MyList(list):
    def __getitem__(self, index):
        if index < 0:
            raise IndexError("list index out of range")
        return super(MyList, self).__getitem__(index)
Run Code Online (Sandbox Code Playgroud)

例:

x = MyList([[1,2,3],[4,5,6],[7,8,9]])
x[-1][0]  # list index of of range -- Good
x[-1][-1] # list index out of range -- Good
x[0][-1]  # returns 3 -- Bad
Run Code Online (Sandbox Code Playgroud)

我该如何解决?我已经研究过可能的解决方案,例如:可以在__getitem__上使用多个参数?.但我无法让它发挥作用.

Tig*_*kT3 6

外部列表是您的自定义类的列表.但是,每个内部列表都是标准list类的列表.为每个列表使用自定义类,它应该工作.

例如:

x = MyList([MyList([1,2,3]), MyList([4,5,6]), MyList([7,8,9])])
Run Code Online (Sandbox Code Playgroud)