簡體   English   中英

在Python2.6中不贊成使用getslice,但在子類化元組時仍然使用它?

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

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

為什么會這樣?

由於歷史原因, __getslice__在某些地方仍然被用於內置類型。 所以對於一個元組,它確實被用於切片的[i:j]樣式語法。 請參閱: http//bugs.python.org/issue2041 ,以獲取簡要說明以及getslice文檔中突出顯示的警告

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM