ABOUT ME

IT와 컴퓨터 관련 팁, 파이썬 등과 아파트 정보, 일상적인 경험 등의 생활 정보를 정리해서 올리는 개인 블로그

  • [python] 파이썬 __init__, __str__, __iter__, __next__ 등의 메서드
    코딩 연습/코딩배우기 2020. 9. 12. 21:01
    반응형

     

    ■ 파이썬의 __init__, __str__, __iter__, __next__ 등의 메서드는 파이썬에 의해 호출되는 메서드로 스페셜 메서드라 한다.

    # 클래스에 스페셜 메서드 정의해보기

    class Car:
        def __init__(self, id):
            self.id = id  # 차량 번호
        
        def __len__(self):
            return len(self.id)
    
        def __str__(self):
            return '차량 번호 : ' + self.id
       
        def __call__(self):
            print('__call__ 함수')
    
    
        
    def main():
        c = Car('12가3456')
        c()  # __call__ 메서드 호출
        print(len(c))  # __len__ 메서드 호출
        print(str(c))  # __str__ 메서드 호출  
        print(c)  # __str__ 메서드 호출  / print(str(c))와 동일
    
    
    main()
    
    
    
    [실행 결과]
    
    __call__ 함수
    7
    차량 번호 : 123456
    차량 번호 : 123456
    

     

    ■ iterable 객체 만들기

    # iterable 객체 조건은 __iter__가 존재해야 한다
    #  __iter__ 함수 추가, for문으로 출력

    class Car:
        def __init__(self, id):
            self.id = id
        
        def __len__(self):
            return len(self.id)
    
        def __str__(self):
            return '차량 번호 : ' + self.id
    
        def __call__(self):
            print('__call__ 함수')
        
        def __iter__(self):
            return iter(self.id)  # iter 함수로 변수 id의 iterator 객체를 반환
    
    
    def main():
        c = Car('34나5678')
        for i in c:  # Car 객체가 iterable 객체라는 증거
            print(i, end=' ')  # 3 4 나 5 6 7 8
    
    
    main()
    
    

     

    good4me.co.kr

     

    ■ iterator 객체 만들기

    # iterator 객체 조건은 __next__가 존재해야 한다.
    # __next__ 함수 추가
    # 값을 하나씩 반환하고, 값이 없으면 StopIteration 예외를 발생시킨다.

    class Coll:
        def __init__(self, values):
            self.values = values  # 인자로 전달된 값 저장
            self.call_count = 0  # __next__ 메서드 호출 횟수
            
        def __next__(self):
            if len(self.values) <= self.call_count:
                raise StopIteration
                
            self.call_count += 1
            return self.values[self.call_count - 1]
        
    
    def main():
        co = Coll([1, 2, 3, 4, 5])  # 리스트, 튜플, 문자열 등 iterable 객체 전달
        while True:
            try:
                i = next(co)
                print(i, end=' ')  # 1 3 5 7 9
            except StopIteration:
                break
    
    main()
    
    

     

    ■ iterable 객체 & iterator 객체 만들기

    class Coll:
        def __init__(self, values):
            self.values = values
            self.call_count = 0
            
        def __next__(self):
            if len(self.values) <= self.call_count:
                raise StopIteration
                
            self.call_count += 1
            return self.values[self.call_count - 1]
        
        def __iter__(self):
            self.call_count = 0  # iter 함수 호출 시 next 호출 횟수 초기화하고,
            return self  # 객체 자체를 반환 --> 몇 번이고 호출 가능토록 함  
        
    
    def main():
        co = Coll([1, 2, 3, 4, 5])  # 리스트, 튜플, 문자열 등 iterable 객체 전달
        for i in co:
            print(i, end=' ')  # 1 2 3 4 5 
        
        for i in co:
            print(i, end=' ')  # 1 2 3 4 5 
    
    main()
    
    

     

    [참고 자료] 윤성우의 열혈파이썬 중급편

     

     

    반응형
Designed by goodthings4me.