考虑以下示例,在 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
为什么会这样?