Python getslice项目操作员覆盖功能不起作用

时间:2016-04-19 19:00:01

标签: python class oop operators

练习发布here的示例来学习Python OOP。我正在寻找' 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",如上面的链接所示。

  

追踪(最近的电话   最后)in()   ----> 1 f [1:4]

     

TypeError:' FakeList'对象不可订阅

1 个答案:

答案 0 :(得分:1)

正如评论中所述,__getitem__方法采用slice类型的一个参数,您可以通过slice.startslice.stop访问范围的开头/结尾是一个示例,其中包含一些调试输出以显示正在发生的事情:

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

输出:

slice_ slice(1, 4, None)

type(slice_) <class 'slice'>

dir(slice_) ['__class__', '__delattr__', '__dir__', '__doc__',
'__eq__', '__format__', '__ge__', '__getattribute__', '__gt__',
'__hash__', '__init__', '__le__', '__lt__', '__ne__', '__new__',
'__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__',
'__str__', '__subclasshook__', 'indices', 'start', 'step', 'stop']

1 to 4
相关问题