我希望扩展“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')
但是它不能正常工作。我无法捕获所有的添加和删除事件。例如:
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']
什么是扩展“list”类的正确方式?谢谢帮助。