또 다른 옵션은 여기에 설명 된대로`collections 모듈에서 적절한 추상 기본 클래스에서 상속하는 것 입니다.
컨테이너가 자체 반복자 인 경우
collections.Iterator. next그런 다음 메서드 를 구현하기 만하면됩니다.
예 :
>>> from collections import Iterator
>>> class MyContainer(Iterator):
... def __init__(self, *data):
... self.data = list(data)
... def next(self):
... if not self.data:
... raise StopIteration
... return self.data.pop()
...
...
...
>>> c = MyContainer(1, "two", 3, 4.0)
>>> for i in c:
... print i
...
...
4.0
3
two
1
당신이보고있는 동안 collections모듈에서 상속 고려 Sequence, Mapping즉 더 적합한 지 또는 다른 추상 기본 클래스입니다. 다음은 Sequence하위 클래스 의 예입니다 .
>>> from collections import Sequence
>>> class MyContainer(Sequence):
... def __init__(self, *data):
... self.data = list(data)
... def __getitem__(self, index):
... return self.data[index]
... def __len__(self):
... return len(self.data)
...
...
...
>>> c = MyContainer(1, "two", 3, 4.0)
>>> for i in c:
... print i
...
...
1
two
3
4.0
NB : 한편으로는 반복기와 다른 한편으로는 반복기보다는 반복 가능한 컨테이너 간의 차이점을 명확히해야한다는 점에주의를 기울여 주신 Glenn Maynard에게 감사드립니다.