简体   繁体   English

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

[英]getslice deprecated in Python2.6, but still in use when subclassing tuple?

Consider the following example, executed under Python 2.6.6 (which I'm unfortunately stuck with at the moment): 考虑下面的例子,在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'>

As it should be, the slicing also call __getitem__ . 应该是这样,切片也调用__getitem__ Now alter the definition to subclassing tuple : 现在将定义更改为子类化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

Why is this happening? 为什么会这样?

Due to historical reasons, __getslice__ in some places still gets used for builtin types. 由于历史原因, __getslice__在某些地方仍然被用于内置类型。 So for a tuple, it does get used for the [i:j] style syntax of slicing. 所以对于一个元组,它确实被用于切片的[i:j]样式语法。 See: http://bugs.python.org/issue2041 for a brief description and the highlighted caveats in the getslice documentation 请参阅: http//bugs.python.org/issue2041 ,以获取简要说明以及getslice文档中突出显示的警告

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM