2014-05-12 2 views
0

파이썬의 목록 개체에있는 모든 설정 메서드가 파생 개체에서 재정의되어 해당 목록의 모든 항목이 특정 클래스에 속할 수 있습니까?단일 클래스 파이썬 목록

class Index(int): 
    pass 


class IndexList(list): 

    def __init__(self, int_list): 
     for el in int_list: 
      self.append(Index(el)) 

    def __setitem__(self, key, val): 
     super(IndexList, self).__setitem__(key, Index(val)) 

    # override append insert etc... 

이 직접 목록에 요소를 추가마다 하나의 함수를 오버라이드 (override)없이 할 수 생각해? 나는 단지 __setitem__을 무시하는 것만으로 충분하다고 생각했다.

예 : append이 무시되지 않는 경우

ilist = IndexList([1,2]) 
ilist.append(3) 

for i in ilist: 
    print(isinstance(i, Index)) # True, True, False 
+0

... 가르치 려주세요) –

+0

난 아직도 내 의도는 잘 사용 여부를 논의하고있다. 내가 계획을 세울수록 더 생각하지 않습니다. – cheezsteak

답변

3

다양하게 직접 구현해야합니다. 동적 인 C 배열을 직접 조작하는 것이 훨씬 효율적이므로 기본 C 구현은 각 변경에 대해 __setitem__을 호출하지 않습니다.

이 방법은 모든 당신이 insert, append, extend__iadd__를 구현해야 것 불변 당신의 유형을 유지하기 위해 목록을 변이 할 수있는 아이디어를 얻기 위해, 특히 MutableSequence ABC에서의 collections abstract base classes에서 살펴 보자.

더 나은 것은 list의 대체 기본 클래스로 collections.MutableSequence() 클래스를 사용할 수 있습니다. 이것은 인 순수 파이썬 구현으로, 많은 메소드를 핵심 메소드 세트에 대한 호출로 캐스트합니다. __len__, __getitem__, __setitem__, __delitem__insert에 대한 구현 만 제공하면됩니다. 테이블의 추상 메서드 열에 명명 된 모든 메서드. 나는 이것에 대한 좋은 사용 사례 생각할 수 없다

class IndexList(collections.MutableSequence): 
    def __init__(self, int_list): 
     self._list = [] 
     for el in int_list: 
      self.append(Index(el)) 

    def __len__(self): return len(self._list) 
    def __getitem__(self, item): return self._list[item] 
    def __delitem__(self, item): del self._list[item] 

    def __setitem__(self, index, value): 
     self._list.key[index] = Index(value) 

    def insert(self, index, value): 
     self._list.insert(index, Index(value))