Python:扩展列表的正确方法

uzu*_*axy 2 python inheritance list

我想扩展类"list"的功能并为事件添加自定义处理程序:"将新项目添加到列表"和"从列表中删除项目".对于这个任务,我不想使用组合,更好的是继承.

我尝试做了什么:

class ExtendedList(list):

    def append(self, obj):
        super(ExtendedList, self).append(obj)
        print('Added new item')

    def extend(self, collection):
        if (hasattr(collection, '__iter__') or hasattr(collection, '__getitem__')) and len(collection)>0:
            for item in collection:
                self.append(item)

    def insert(self, index, obj):
        super(ExtendedList, self).insert(index, obj)
        print('Added new item')

    def remove(self, value):
        super(ExtendedList, self).remove(value)
        print('Item removed')
Run Code Online (Sandbox Code Playgroud)

但它无法正常工作.我无法捕捉所有添加和删除事件.例如:

collection = ExtendedList()
collection.append('First item')
# Out: "Added new item\n"; collection now is: ['First item']
collection.extend(['Second item', 'Third item'])
# Out: "Added new item\nAdded new item\n"; collection now is: ['First item', 'Second item', 'Third item']
collection += ['Four item']
# Don't out anythink; collection now is: ['First item', 'Second item', 'Third item', 'Four item']
collection.remove('First item')
# Out: "Item removed\n"; collection now is: ['Second item', 'Third item', 'Four item']
del collection[0:2]
# Don't out anythink; collection now is: ['Four item']
collection *= 3
# Don't out anythink; collection now is: ['Four item', 'Four item', 'Four item']
Run Code Online (Sandbox Code Playgroud)

为我的情况扩展课程"列表"的正确方法是什么?感谢帮助.

jon*_*rpe 5

而不是继承list自己,继承自它的抽象基类,collections.MutableSequence.这将为您完成所有基本工作,让您专注于您想要改变的内容.有对基本知识一个很好的问题在这里.