简体   繁体   中英

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):

>>> 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__ . Now alter the definition to subclassing 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. So for a tuple, it does get used for the [i:j] style syntax of slicing. See: http://bugs.python.org/issue2041 for a brief description and the highlighted caveats in the getslice documentation

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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