"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