본문 바로가기
Python/기초

[파이썬/Python] Iterable과 Iterator 객체를 만들어 보자.

by 모두의 케빈 2023. 7. 6.

Iterable, Iterator 객체 구현을 위한 개념 정리


 

이전 시간에는 Iterable, Iterator 객체에 대해 살펴봤습니다. 두 객체를 만들기 위해 필요한 개념을 다시 한번 정리해 보겠습니다.

 

Iterable 객체

1. 내부에 __iter__ 메서드가 있어야 한다.

2. __iter__ 메서드는 Iterator를 반환한다.

3. 순회할 수 있도록 시작과 마지막에 대한 정보가 있어야 한다. (이해를 위해 추가)

 

Iterator 객체

1. Iterable 객체의 __iter__ 메서드를 통해 생성된다.

2. 내부에 __next__ 메서드가 있다.

3. __next__ 메서드를 통해 다음 값을 호출한다.

4. 순회를 위해 시작값과 마지막에 대한 정보가 있어야 한다. (이해를 위해 추가)

5. 현재 상태가 존재한다. 이를 확인할 수 있도록 현재 index에 대한 정보가 있어야 한다.

6. 마지막 원소를 반환하면, StopIterator 에러를 발생시킨다.

 

위의 조건을 토대로 직접 Iterable과 Iterator 객체를 만들어서 for문에 대입해 보도록 하겠습니다.

 

 

 

Iterable, Iterator 객체 구현 코드


 

1부터 5까지 출력하는 가장 간단한 Iterable, Iterator 객체를 만들어 보도록 하겠습니다. 먼저 Iterable 객체를 위 조건에 따라 만들었습니다.

class Custom_Iterable:
    def __init__(self, start, end):
        self.start = start
        self.end = end
        
    def __iter__(self):
        return Custom_Iterator(self.start, self.end)

 

만들어진 객체가 Iterable 객체가 맞는지 확인해 보겠습니다. typing 모듈에서 Iterable 함수를 통해 확인할 수 있습니다.

from typing import Iterable

custom_Iterable = Custom_Iterable(1,5)
print(isinstance(custom_Iterable, Iterable)) # True

 

다음으로 Iterator 객체를 구현해 보겠습니다. 

class Custom_Iterator:
    def __init__(self, start, end):
        self.start = start
        self.cur = start
        self.end = end
        
    def __next__(self):
        if self.cur <= self.end:
            self.cur += 1
            return self.cur-1
        else:
            raise StopIteration

 

 

이제 Iterable 객체를 for문에 대입해 보겠습니다.

custom_Iterable = Custom_Iterable(1,5)

for i in custom_Iterable:
    print(i)
    
    
# 위 코드의 결과값
1
2
3
4
5

 

위 for문의 작동 원리를 수동으로 바꾸면 아래와 같습니다.

custom_Iterable = Custom_Iterable(1,5)
custom_Iterator = custom_Iterable.__iter__()

custom_Iterator.__next__() # 1
custom_Iterator.__next__() # 2
custom_Iterator.__next__() # 3
custom_Iterator.__next__() # 4
custom_Iterator.__next__() # 5
#custom_Iterator.__next__() # StopIteration

 

댓글