13

I want to subclass the list type and have slicing return an object of the descendant type, however it is returning a list. What is the minimum code way to do this?

If there isn't a neat way to do it, I'll just include a list internally which is slightly more messy, but not unreasonable.

My code so far:

class Channel(list):
    sample_rate = 0
    def __init__(self, sample_rate, label=u"", data=[]):
        list.__init__(self,data)
        self.sample_rate = sample_rate
        self.label = label

    @property
    def nyquist_rate(self):
        return float(self.sample_rate) / 2.0
user
  • 5,370
  • 8
  • 47
  • 75
SapphireSun
  • 9,170
  • 11
  • 46
  • 59

1 Answers1

11

I guess you should override the __getslice__ method to return an object of your type...

Maybe something like the following?

class MyList(list):
    #your stuff here

    def __getslice__(self, i, j):
        return MyList(list.__getslice__(self, i, j))
fortran
  • 74,053
  • 25
  • 135
  • 175
  • Could one use seattr for this ? A naive `setattr(self, '__getslice__', lambda *a, **k: whatever()` fails) - see http://stackoverflow.com/q/29858405/281545 – Mr_and_Mrs_D Apr 24 '15 at 22:14