[디자인패턴] Python Iterator Pattern

김유상·2022년 10월 28일
0

디자인패턴

목록 보기
1/2

Referenced: https://www.youtube.com/watch?v=T3sXKtlr0Ow&list=PLe6NQuuFBu7FhPfxkjDd2cWnTy2y_w_jZ&index=2
위 영상을 참고해서 Python으로 학습했다.

Iterator Pattern은 본인이 정의한 객체가 iterable하고 실제로 리스트처럼 사용해야 한다면 다음과 같이 iterator를 정의해서 사용할 수 있다.

사실 Python의 List 자료구조는 어떤 객체든 삽입될 수 있어 굳이 이렇게 iterable한 클래스를 만들 필요는 없을 지도 모른다...

class Item:
    def __init__(self, name, cost):
        self._name = name
        self._cost = cost

    def __str__(self):
        return "(" + self._name + ", " + str(self._cost) + ")"

class Array:
    def __init__(self, items):
        self._items = items

    def __iter__(self):
        return ArrayIterator(self)

    def get_item(self, index):
        return self._items[index]

    def get_count(self):
        return len(self._items)

class ArrayIterator:
    def __init__(self, array):
        self._array = array
        self._index = -1

    def __next__(self):
        self._index += 1
        if self._index >= self._array.get_count():
            raise StopIteration
        return self._array.get_item(self._index)

if __name__ == "__main__":
    items = [Item("CPU", 1000), Item("Keyboard", 2000), Item("Mouse", 3000), Item("HDD", 50)]

    array = Array(items)

    for item in array:
        print(str(item))
profile
continuous programming

0개의 댓글