Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Subclass builtin List

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
like image 975
SapphireSun Avatar asked Feb 10 '10 09:02

SapphireSun


People also ask

How do I get all the subclasses in Python?

If you do have a string representing the name of a class and you want to find that class's subclasses, then there are two steps: find the class given its name, and then find the subclasses with __subclasses__ as above. However you find the class, cls. __subclasses__() would then return a list of its subclasses.

How do you make a class list in Python?

We can create list of object in Python by appending class instances to list. By this, every index in the list can point to instance attributes and methods of the class and can access them. If you observe it closely, a list of objects behaves like an array of structures in C.


1 Answers

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))
like image 181
fortran Avatar answered Oct 01 '22 03:10

fortran