Good day. There is a class with a container. I want to make a cut from the class instance, as if I turned to the list. How can this be implemented without inheriting from the list class, and possibly using magic methods?

class L: def __init__(self): self.__lst = [] l = L() l[:] 

    2 answers 2

    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

       class L: def __getitem__(self, i): # Перегружаем [] if isinstance(i, slice): # Проверяем на срез ... # Необходимые действия return self.__lst[i]