Subclass builtin List

ε祈祈猫儿з 提交于 2020-01-22 17:28:05

问题


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

回答1:


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))


来源:https://stackoverflow.com/questions/2235556/subclass-builtin-list

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!