파이썬 중급 8일차

김영목·2021년 8월 26일
0

파이썬중급

목록 보기
14/18

오늘 공부할 내용은 iterator와 generator이다.

1교시 : iterator에 대해서 공부하기 전에 iter타입에 대해서 알아보자.


우리가 알고 있는 반복문에 사용할 수 있는 자료형 혹은 타입은 str, list, dict, tuple등이 있다. 

만약 우리가 어떤 객체를 보고 해당 객체가 반복가능한 객체인지 알아보기 위해서는 dir(객체)를 해보면된다. 

from collections import abc

t = 'asdgedsghh'

#for 반복

for i in t :
	print(c)

#while반복

w = iter(t)

while True :
	try :
    		print(next(w))
    
    	except stopiteration :
        	break
            
반복형 가능성 확인
기본 : print(dir(t))

중급 : print(hasattr(t, '__iter__'))

고급 : print(isinstance(t, abc.iterable))

위의 3가지 방법을 통해서 해당 객체가 반복가능한 객체인지 확인할 수 있다. 

자, 이번에는 for를 이용하지 않고 반복가능한 객체를 마치 반복문을 사용한 것처럼 출력해보자. 

t = 'absdecxx'


def make_forloop(args):
    args = iter(args)
    while True:
        try:
            print(next(args))

        except StopIteration:
            break


if __name__ == '__main__':
    make_forloop(t)
    
또 다른 예제를 만들어보자.

class my_work2():

    def __init__(self, text):

        self._text = text.split(' ')
        self._idx = 0

    def __next__(self):
        try:
            word = self._text[self._idx]

        except IndexError:
            raise StopIteration

        self._idx += 1
        return word

    def __repr__(self):
        return f'you input {self._text}'
        
 여기서 주의할 점은 def __call__이 아니라 def __next__로 함수 이름을 주어야한다. 
 
 
 2교시 : generater를 만들어보자. 
 
 class my_gen (args) :
 	
    def __init__(self, text) :
    	self.text = text.split(' ')
        
    def __iter__(self) :
    	
        for word  in self.text :
        	yield  word
            
    def __repr__(self) :
    	return f'you input {self.text}'


w = my_gen('i am youngmok')

print(next(w))

 	

      
profile
안녕하세요 김영목입니다.

0개의 댓글