在Python中创建自定义类列表

时间:2015-03-24 22:46:09

标签: python list class

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

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

class CommentList(list):
    def append(self, other):
         return self.data_list.append(other)

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

5 个答案:

答案 0 :(得分:6)

最简单的实现方式是:

class CommentList(list):

    def append(self, val):
        super(CommentList, self).append(val)
        self.sort()

这样做你想要的:

>>> l = CommentList((2, 3, 4))
>>> l.append(5)
>>> l
[2, 3, 4, 5]
>>> l.append(1)
>>> l
[1, 2, 3, 4, 5]

但请注意,还有其他方法可以将数据导入列表(__add__extend__setitem__);它们应该涉及分类吗?应该例如一片CommentList是另一个CommentList,还是一个香草listCommentList看起来与香草列表完全相同,因为它继承了__repr__,但这可能会产生误导。子类化内置类型可能很复杂;你应该从MutableSequence abstract base class开始,而不是。

答案 1 :(得分:2)

只需使用超级调用,然后添加排序函数调用:

class CommentList(list):
    def append(self, other):

        # call the append of the parent class
        # which of course is the builtin list

        super(CommentList, self).append(other)

        # then call the sort method that we 
        # just inherited from the parent 

        self.sort() # sort after using append

答案 2 :(得分:0)

class CommentList(list):
    def append(self, other):
         r = super(CommentList, self).append(other)
         self.sort()
         return r

答案 3 :(得分:0)

在我看来,它会很漂亮" unpythonic"去做这个。没有理由使用继承,你可以在每次追加后返回一个排序列表。

也就是说,通常不需要对列表进行排序,直到它被填充为止。在这种情况下,构建您的列表,然后通过为其分配sorted(original_list)来设置sorted_list。

在任何一种情况下,您都必须确定对列表进行排序的含义。

您还必须担心如何处理:

a = list () a.append (19) a.append ('my birthday')

答案 4 :(得分:0)

你可以做到这一点,但几乎肯定不是你想要的。除其他原因外,append()只是列表元素改变的一种方式。例如, setitem (),insert()和extend()。如果您希望“列表已排序”为不变量,则需要覆盖所有这些方法。您可能无意使用这些方法。如果是这样,您可以创建一个包含列表的对象,并且只显示您想要的方法。

如果性能是个问题,您可能希望更改为直接支持维护排序顺序的数据结构,如堆或树。

如果你真的想要一个像列表一样工作的对象但是有追加触发排序的额外功能,你所拥有的东西会起作用,但这是一种奇怪的行为。