The slice is implemented through the __getitem__
method (the same method as for taking an element by index). When performing a slice, a special object of the slice
class is passed to this method. Example of implementation:
class L: def __init__(self, lst=None): if not lst: self.__lst = [] else: self.__lst = lst def __getitem__(self, item): if isinstance(item, slice): # Создание нового объекта данного класса с элементами среза внутреннего списка return self.__class__(self.__lst[item.start:item.stop:item.step]) # или return self.__class__(self.__lst[item])) else: return L.__lst[item] def __repr__(self): return 'L(%r)' % self.__lst x = L(list(range(10))) print(x) # Вывод: L([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]) print(x[2:5]) # Вывод: L([2, 3, 4])
Assigning to a slice and deleting a slice is implemented in the same way using the __setitem__
and __delitem__
.
Add. Information: Habrahabr: Everything you wanted to know about slices