Python getslice Item Operator Override函数不工作

2024-10-01 00:31:38 发布

您现在位置:Python中文网/ 问答频道 /正文

练习为学习pythonoop而发布的here示例。我正在查找“1到4”的输出,但它引发以下错误。在

class FakeList:
     def __getslice___(self,start,end):
         return str(start) + " to " + str(end)

f = FakeList()

f[1:4]

注意:使用f.__getitem__(1, 4)会得到正确的输出--“1到4”,如上面的链接所示。在

Traceback (most recent call last) in () ----> 1 f[1:4]

TypeError: 'FakeList' object is not subscriptable


Tags: toself示例returnheredef错误start
1条回答
网友
1楼 · 发布于 2024-10-01 00:31:38

如注释中所述,__getitem__方法接受一个slice类型的参数,您可以通过slice.start和{}访问范围的开始/结束,下面是一个示例,其中有一些更多的调试输出,以显示正在进行的操作:

class FakeList:

    def __getitem__(self, slice_):
         print('slice_', slice_)
         print('type(slice_)', type(slice_))
         print('dir(slice_)', dir(slice_))
         return str(slice_.start) + " to " + str(slice_.stop)

f = FakeList()

print(f[1:4])

输出:

^{pr2}$

相关问题 更多 >