λ³Έλ¬Έ λ°”λ‘œκ°€κΈ°
IT/Python

[Python] μ΄ν„°λ ˆμ΄ν„°(Iterator)_ν”„λ‘œκ·Έλž¨

by ITyranno 2023. 11. 17.
728x90
λ°˜μ‘ν˜•

 

 

 

 

 

 

ν”„λ‘œκ·Έλž˜λ° 세계λ₯Ό νƒκ΅¬ν•©μ‹œλ‹€.

 

 

 

<μ΄ν„°λ ˆμ΄ν„°(Iterator)>
νŒŒμ΄μ¬μ—μ„œ 반볡 κ°€λŠ₯ν•œ 객체(클래슀)λ₯Ό ν‘œν˜„ν•˜λŠ”λ° μ‚¬μš©λ˜λŠ” μΈν„°νŽ˜μ΄μŠ€ μ΄ν„°λ ˆμ΄ν„°λŠ” iter()ν•¨μˆ˜μ™€ next()ν•¨μˆ˜λ₯Ό μ΄μš©ν•˜μ—¬ 반볡(Inerator)을 μˆ˜ν–‰

 

 

 

 

<μž‘μ„± μ½”λ“œ>

 

 

### 클래슀 μ •μ˜ν•˜κΈ°
class MyIterator : 
    ### 클래슀 μƒμ„±μž μ •μ˜ν•˜κΈ°
    def __init__(self) :
        self.current_value = 0
        print(f"#1(__init__) : self = {self} / self.current_value={self.current_value}")
        
    ### μžμ‹ μ˜ 클래슀λ₯Ό λ°˜ν™˜ν•˜λŠ” iter ν•¨μˆ˜ μ •μ˜
    def __iter__(self) : 
        print(f"#2(__iter__) : self = {self}")
        return self
        
    ### λ°˜λ³΅μ„ μˆ˜ν–‰ν•˜λŠ” next ν•¨μˆ˜ μ •μ˜
    def __next__(self) : 
        print(f"#3(__next__) : self = {self}")
        # - current_value 의 값을 5 보닀 μž‘μ„ λ•Œ κΉŒμ§€λ§Œ 반볡 μˆ˜ν–‰
        if self.current_value < 5: 
            # - λ±ν™˜ν•  ν•¨μˆ˜μ— current_value의 ν˜„μž¬ κ°’ μ €μž₯
            result = self.current_value
            # - current_value ν˜„μž¬ 값을 1 증가
            self.current_value += 1 

            print(f"#4(__next__) : self.current_value = {self.current_value}")
            # - returen κ°’ λ°˜ν™˜
            return result
        else :
            print("#5 : StopIteration μ˜ˆμ™Έ λ°œμƒ!!") 
            ### μ΄ν„°λ ˆμ΄ν„°λŠ” 반볡이 λλ‚˜λ©΄ μ’…λ£Œ μ‹œμΌœμ•Ό ν•©λ‹ˆλ‹€. 
            # - μ’…λ£Œ μ‹œν‚€λŠ” 방법은 κ°•μ œλ‘œ 였λ₯˜λ₯Ό λ°œμƒμ‹œν‚΄(StopIteration)
            raise StopIteration

 

 

### μ΄ν„°λ ˆμ΄ν„° μ‹€ν–‰μ‹œν‚€κΈ°
# - 클래슀 μƒμ„±ν•˜κΈ°
my_iterator = MyIterator()

 

 

 

<μ‹€ν–‰ ν™”λ©΄>

 

 

 

 

 

<μž‘μ„± μ½”λ“œ>

 

### μ΄ν„°λ ˆμ΄ν„° κΈ°λŠ₯은 반볡문(for or while)을 μ‚¬μš©ν•΄μ•Όλ§Œ μž‘λ™ν•˜λŠ” κΈ°λŠ₯μž„
# - 졜초 __iter__() ν•¨μˆ˜λ₯Ό ν˜ΈμΆœν•˜κ³ ,
# - 좜λ ₯ μ‹œ __next__()ν•¨μˆ˜κ°€ ν•œλ²ˆμ”© μˆ˜ν–‰ν•˜λ©΄μ„œ 값을 λ°˜ν™˜λ°›μ•„μ„œ 좜λ ₯함
# - ν•œλ²ˆ λ°˜ν™˜λœ ν›„ λ©”λͺ¨λ¦¬λŠ” μ΄ˆκΈ°ν™”λ˜λ©°, λ‹€μŒ λ°˜λ³΅μ‹œ λ‹€μ‹œ λ©”λͺ¨λ¦¬ μ‚¬μš©
# ** λ©”λͺ¨λ¦¬λ₯Ό 효율적으둜 ν™œμš©ν•  수 있음
# 반볡 μˆ˜ν–‰ν•˜μ—¬ result κ°’ 좜λ ₯ν•˜κΈ°
for value in my_iterator :
    print(value)

 

 

 

<μ‹€ν–‰ ν™”λ©΄>

 

 

 

 

<μž‘μ„± μ½”λ“œ>

 

### μ΄ν„°λ ˆμ΄ν„° μ‹€ν–‰μ‹œν‚€κΈ°
# - 클래슀 μƒμ„±ν•˜κΈ°
my_iterator = MyIterator()

 

 

 

<적용 ν™”λ©΄>

 

 

 

 

<μž‘μ„± μ½”λ“œ>

 

print(next(my_iterator))

 

 

 

<적용 ν™”λ©΄>

 

 

 

 

<μž‘μ„± μ½”λ“œ>

 

try :
    print(next(my_iterator))
    print(next(my_iterator))
    print(next(my_iterator))
except :
    print("μ΄ν„°λ ˆμ΄ν„°κ°€ μ’…λ£Œλ˜μ—ˆμŠ΅λ‹ˆλ‹€.")

 

 

 

<μ‹€ν–‰ ν™”λ©΄>

 

 

 

 

 

 

728x90
λ°˜μ‘ν˜•

loading