gpt4 book ai didi

Python、__getitem__、切片和负索引

转载 作者:行者123 更新时间:2023-12-01 04:40:11 26 4
gpt4 key购买 nike

这是 Python 在切片中传递负数的行为示例:

>>> class test:
... def __getitem__(self, sl):
... print sl.start, sl.stop, sl.step
...
>>> t = test()
>>> t[0:0:0]
0 0 0
>>> t[-1:0]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: test instance has no attribute '__len__'
>>> def __len__(self): return 100
...
>>> test.__len__ = __len__
>>> t[-1:0]
99 0 None
>>>

我想自己处理负索引。如何让 Python 停止自动决定切片索引?

最佳答案

在Python 2.x中,需要通过子类化object来使用新式类,然后才能得到切片的原始参数:

>>> class C(object):
... def __getitem__(self, key):
... print key
...
>>> c = C()
>>> c[-1:2]
slice(-1, 2, None)

在2.x之前,有一种专用的切片方法,__getslice__ ,Python 2.x 中仍然支持它,并使用 __len__ 进行插值:

Called to implement evaluation of self[i:j]. The returned object should be of the same type as self. Note that missing i or j in the slice expression are replaced by zero or sys.maxsize, respectively. If negative indexes are used in the slice, the length of the sequence is added to that index. If the instance does not implement the __len__() method, an AttributeError is raised. No guarantee is made that indexes adjusted this way are not still negative. Indexes which are greater than the length of the sequence are not modified. If no __getslice__() is found, a slice object is created instead, and passed to __getitem__() instead.

(强调我的)

关于Python、__getitem__、切片和负索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30874047/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com