yield文
return文のように関数やメソッドで用いられ、呼び出し元に値を返す文である。
return文は関数の処理をメモリ上から削除するのに対し、yield文は関数の処理を残したまま処理の流れを呼び出し元に返す。呼び出される度に前回実行されたyield文の直後から処理を再開する。
code:python
def myfunc():
print('# step-1')
yield 1
print('# step-2')
yield 2
print('# step-3')
yield 3
for i in myfunc():
print(i)
range型オブジェクトやzipオブジェクトのように、for文を用いることにより先頭から順に値を取り出すことができる。
rangeオブジェクトやzipオブジェクトのように、リスト型にキャストすると、yield文で返す全ての値をり出すことができる。
code:python
def myfunc():
print('# step-1')
yield 1
print('# step-2')
yield 2
print('# step-3')
yield 3
x = list(myfunc())
print('# Result:')
print(x)
# step-1
# step-2
# step-3
# Result:
1, 2, 3
rangeオブジェクトやzipオブジェクトのように、関数を呼び出すとオブジェクトに関する属性が得られる。yeield文が返す値は得られない。
code:python
def myfunc():
print('# step-1')
yield 1
print('# step-2')
yield 2
print('# step-3')
yield 3
print(myfunc())
print(myfunc())
print(myfunc())
# <generator object myfunc at 0x7fc05a1f02e0>
# <generator object myfunc at 0x7fc05a1f02e0>
# <generator object myfunc at 0x7fc05a1f02e0>