考虑下面的例子,在Python 2.6.6下执行(我不幸的是当时这个例子):
>>> class A:
... def __getitem__(self, index):
... print(type(index))
... def __getslice__(self, start, end):
... print("Don't call me, I'm deprecated")
...
>>> a = A()
>>> a[3]
<type 'int'>
>>> a[3:3]
<type 'slice'>
应该如此,切片也会调用__getitem__
。
现在将定义更改为继承tuple
:
>>> class B(tuple):
... def __getitem__(self, index):
... print(type(index))
... def __getslice__(self, start, end):
... print("Don't call me, I'm deprecated")
...
>>> b = B()
>>> b[3]
<type 'int'>
>>> b[3:]
Don't call me, I'm deprecated
为什么会这样?
答案 0 :(得分:2)
由于历史原因,某些地方的__getslice__
仍然用于内置类型。因此对于元组,它确实用于切片的[i:j]
样式语法。有关简要说明和http://bugs.python.org/issue2041