ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • 파이썬 Iterator & Generator
    CS/공통 2022. 3. 12. 19:04
    728x90

    Iterator

    반복자

     

    과정은 다음과 같다.

    x = [1,2,3]   --iter()-->  iterator -> 1,2,3

     

    클래스에서 이터러블 객체가 되려면 2개의 메소드를 구현해야한다.

    1. __iter__()   #이터러블 객체 자신을 반환한다.

    2. __next__()  #다음 반복을 위한 값을 반환한다. 더이상 값이 없으면 StopIteratoin 예외발생

     

    예시코드

    class Counter(object):
        def __init__(self, low, high):
            self.low = low
            self.high = high
            
        def __iter(self):
            return self
        
        def __next__(self):
            if self.low > self.high:
                raise StopIteration
            
            else:
                self.low += 1
                return self.low -1

    Generator

    키워드 yield를 사용하여 이터레이터를 생성시키는  하나의 방법

     

     

    이터레이터는 클래스를 이용한 이터러블 객체를 생성하는 것이고, 제네레이터는 함수를 이용하여 이터러블 객체를 생성하는 것

    def CounterGen(low,high):
        while low <= high:
            yield low
            low += 1
        
    for i in CounterGen(5, 14):
        print(i, end=' ')
    728x90

    'CS > 공통' 카테고리의 다른 글

    파이썬 코딩 스타일 가이드라인 PEP8  (0) 2022.04.26

    댓글

oguuk Tistory.