在Python2.6中不赞成使用getslice,但在子类化元组时仍然使用它?

时间:2013-05-14 18:20:51

标签: python python-2.6 slice

考虑下面的例子,在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

为什么会这样?

1 个答案:

答案 0 :(得分:2)

由于历史原因,某些地方的__getslice__仍然用于内置类型。因此对于元组,它确实用于切片的[i:j]样式语法。有关简要说明和http://bugs.python.org/issue2041

中突出显示的警告,请参阅:the getslice documentation
相关问题