Customize Python Slicing, please advise

醉酒当歌 提交于 2019-12-01 04:04:52

See this note:

object.__getslice__(self, i, j)

Deprecated since version 2.0: Support slice objects as parameters to the __getitem__() method. (However, built-in types in CPython currently still implement __getslice__(). Therefore, you have to override it in derived classes when implementing slicing.

So, because you subclass list you have to overwrite __getslice__, even though it's deprecated.

I think you should generally avoid subclassing builtins, there are too many weird details. If you just want a class that behaves like a list, there is a ABC to help with that:

from collections import Sequence

class MyList(Sequence):
    def __init__(self, *items):
        self.data = list(items)

    def __len__(self):
        return len(self.data)

    def __getitem__(self, slice):
        return self.data[slice]

s = MyList(1,2,3)
# lots of free methods
print s[1:2], len(s), bool(s), s.count(3), s.index(2), iter(s)
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!