2

I'm trying to create a class that behaves exactly as a slice, but that implements the __add__ method to combine multiple slices in a single slice.

A simple mockup could be:

class cumslice(slice):
    def __add__(self, other):

        s1  = self.start
        e1  = self.end
        st1 = self.step

        s2  = other.start
        e2  = other.end
        st2 = other.step

        s = s1 + st1*s2
        st = st1*st2
        e = min([e1, s1 + st1*e2])

        return cumslice(s, e, st)

(note that we need some if to handles None values.)

However the code above returns

TypeError: type 'slice' is not an acceptable base type

Is it possible to do something like this without reimplementing the slice type from scratch?

Luca
  • 1,610
  • 1
  • 19
  • 30
  • 2
    `slice` is implemented as "final" and cannot be subclassed – hurlenko Feb 12 '20 at 10:29
  • 1
    Use composition instead of inheritance if the latter is not possible. – sanyassh Feb 12 '20 at 10:29
  • @sanyash can you explain what this means? – Luca Feb 12 '20 at 10:37
  • do in your class the following: `self._slice = slice(start, stop, end)` and get `self._slice.start` instead of `self.start` when inheriting from `slice`. – sanyassh Feb 12 '20 at 10:39
  • @sanyash Doing this `x[cumslice(0,10,2)]` would raise the exception `TypeError: list indices must be integers or slices, not cumslice`. I know I could do `x[cumslice(0,10,2)._slice]`, but this would require all the following code to be changed. – Luca Feb 12 '20 at 10:49
  • Ok, I realized that it is not as easy as it seemed. – sanyassh Feb 12 '20 at 11:17
  • Does this answer your question? [Make an object that behaves like a slice](https://stackoverflow.com/questions/39971030/make-an-object-that-behaves-like-a-slice) – sanyassh Feb 12 '20 at 11:35
  • @sanyash if the answer is “you can’t“, then unfortunately yes. It does answer – Luca Feb 12 '20 at 22:55

0 Answers0