在Python中创建自定义类列表

0 python class list

我正在尝试创建一个自定义列表子类,它继承列表类的所有方面,除了它的append方法在每次添加新对象时对列表进行排序.

到目前为止,我有这样的事情:

class CommentList(list):
    def append(self, other):
         return self.data_list.append(other)
Run Code Online (Sandbox Code Playgroud)

我不确定如何为此引入排序功能以及如何改进上述方法.

jon*_*rpe 8

最简单的实现方式是:

class CommentList(list):

    def append(self, val):
        super(CommentList, self).append(val)
        self.sort()
Run Code Online (Sandbox Code Playgroud)

这样做你想要的:

>>> l = CommentList((2, 3, 4))
>>> l.append(5)
>>> l
[2, 3, 4, 5]
>>> l.append(1)
>>> l
[1, 2, 3, 4, 5]
Run Code Online (Sandbox Code Playgroud)

但是请注意,有其他的方法来获取数据到列表(__add__,extend,__setitem__); 它们应该涉及分类吗?例如,一片CommentList是另一片CommentList还是香草list?A CommentList看起来完全像香草列表,因为它继承了__repr__,但这可能会产生误导.子类化内置类型可能很复杂; 你应该从MutableSequence抽象基类开始.