__getitem__ 方法接收 int 而不是 slice obj

__getitem__ method receives int instead of slice obj

在自定义 class 中实现 __getitem__ 方法时,我希望第二个参数始终是切片对象。

然而,当执行 obj[i] 其中 i 是一个整数时,obj.__getitem__(self,value) 收到一个 int 而不是一个切片。

这可以做测试

class MyClass:

    def __getitem__(self, sliceobj):
        print(type(sliceobj))

a = MyClass()

a[1:5]
a[2:]
a[::2]
a[0]

>> <class 'slice'>
>> <class 'slice'>
>> <class 'slice'>
>> <class 'int'>

这给我带来了问题,因为我的 class 有一个内部列表(在 __init__ 中定义),我想使用切片对其进行迭代。问题是当 sliceint.

时,list[slice] 的输出不是可迭代的

换句话说:

class MyClass2:

    def __getitem__(self, sliceobj):

        a_list = [1,2,3,4]

        print(sliceobj)

        for val in a_list[sliceobj]:
            # do stuff
            pass

        print('it worked')

a = MyClass2()

a[1:3]
a[2:]
a[::2]
a[0]

适用于前 3 个调用,但不适用于最后一个,因为 a_list[0] 不可迭代。

a[0] 不应该翻译成 a.__getitem__(slice(0,1)) 吗?

根据the docs

For sequence types, the accepted keys should be integers and slice objects

您可以检查键是否是切片并创建一个:

class MyClass2:
    def __getitem__(self, key):

        a_list = [1,2,3,4]
        keys_to_iterate = key if isinstance(key, slice) else slice(key, key+1)
        print(key)

        for val in a_list[keys_to_iterate]:
            # do stuff
            pass

        print('it worked')

运行 示例:https://repl.it/repls/SmallDarkblueWifi