Generator
์ ๋๋ ์ดํฐ Generator
์ดํฐ๋ ์ดํฐ๋ฅผ ์ง์ ๋ง๋ค ๋ ์ฌ์ฉํ๋ ์ฝ๋๋ก์จ, ํจ์ ๋ด๋ถ์ yield ํค์๋๋ฅผ ์ฌ์ฉํ๋ฉด ํด๋น ํจ์๋ ์ ๋๋ ์ดํฐ ํจ์๊ฐ ๋๋ฉฐ,
์ผ๋ฐ ํจ์์ ๋ฌ๋ฆฌ ํจ์๋ฅผ ํธ์ถํด๋ ํจ์ ๋ด๋ถ์ ์ฝ๋๊ฐ ์คํ๋์ง ์๋๋ค
์ ๋๋ ์ดํฐ ๊ฐ์ฒด๋ next() ํจ์๋ฅผ ์ฌ์ฉํด ํจ์ ๋ด๋ถ์ ์ฝ๋๋ฅผ ์คํํ์ฌ์ผ ํ๋ค
def test(): print("ํจ์๊ฐ ํธ์ถ๋์์ต๋๋ค.") yield test print("A ์ง์ ํต๊ณผ") test() print("B ์ง์ ํต๊ณผ") test() print(test()) # A ์ง์ ํต๊ณผ # B ์ง์ ํต๊ณผ # <generator object test at 0x000001981619B9C8>
์ ๋๋ ์ดํฐ ๊ฐ์ฒด์ next() ํจ์
next() ํจ์๋ฅผ ํธ์ถํ ์ดํ yield ํค์๋๋ฅผ ๋ง๋์ง ๋ชปํ๊ณ ํจ์๊ฐ ๋๋๋ฉด
StopIteration์ด๋ผ๋ ์์ธ๊ฐ ๋ฐ์ํ๋ค
def test():
print("A ์ง์ ํต๊ณผ")
yield 1
print("B ์ง์ ํต๊ณผ")
yield 2
print("C ์ง์ ํต๊ณผ")
output = test()
print("D ์ง์ ํต๊ณผ")
a = next(output)
print(a)
print("E ์ง์ ํต๊ณผ")
b = next(output)
print(b)
print("F ์ง์ ํต๊ณผ")
c = next(output)
print(c)
next(output)
# D ์ง์ ํต๊ณผ
# A ์ง์ ํต๊ณผ
# 1
# E ์ง์ ํต๊ณผ
# B ์ง์ ํต๊ณผ
# 2
# F ์ง์ ํต๊ณผ
# C ์ง์ ํต๊ณผ
# => error ๋ฐ์
Traceback (most recent call last):
File "test.py", line 18, in <module>
c = next(output)
StopIteration
Last updated
Was this helpful?