我想擴展類「list」的功能,併爲事件添加自定義處理程序:「添加新項目到列表」和「從列表中刪除項目」。對於這個任務我不想使用組合,更好的是繼承。Python:擴展列表的正確方式
什麼,我試圖做的事:
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']
什麼是正確的方式來擴展我的情況類「列表」?感謝幫助。
在這裏定義列表的子類不是一個好主意。相反,你應該傾向於繼承聚合 – gefei
這些都做不同的事情,所以使用一個更適合你想要完成的事情? – brandonscript
你已經展示了會發生什麼,但是它有什麼問題?你想要發生什麼? – nmichaels