方法がわかりませんsend。ジェネレーターの操作に使用されていることを理解しています。ただし、構文は次のとおりですgenerator.send(value)。
どういうわけか、値が現在のyield式の結果になる必要がある理由を理解できません。私は例を用意しました:
def gen():
for i in range(10):
X = yield i
if X == 'stop':
break
print("Inside the function " + str(X))
m = gen()
print("1 Outside the function " + str(next(m)) + '\n')
print("2 Outside the function " + str(next(m)) + '\n')
print("3 Outside the function " + str(next(m)) + '\n')
print("4 Outside the function " + str(next(m)) + '\n')
print('\n')
print("Outside the function " + str(m.send(None)) + '\n') # Start generator
print("Outside the function " + str(m.send(77)) + '\n')
print("Outside the function " + str(m.send(88)) + '\n')
#print("Outside the function " + str(m.send('stop')) + '\n')
print("Outside the function " + str(m.send(99)) + '\n')
print("Outside the function " + str(m.send(None)) + '\n')
結果は次のとおりです。
1 Outside the function 0
Inside the function None
2 Outside the function 1
Inside the function None
3 Outside the function 2
Inside the function None
4 Outside the function 3
Inside the function None
Outside the function 4
Inside the function 77
Outside the function 5
Inside the function 88
Outside the function 6
Inside the function 99
Outside the function 7
Inside the function None
Outside the function 8
まあ、率直に言って、それは私を驚かせています。
- ドキュメントでは、
yieldステートメントが実行されると、ジェネレーターの状態がフリーズし、の値がの呼び出し元expression_listに返されることがわかります。nextまあ、それは起こっていないようです。なぜifステートメントとprint関数を内部で実行できるのですかgen()。 X関数の内部と外部が異なる理由をどのように理解できますか?Ok。send(77)77をに送信すると仮定しmます。さて、yield式は77になります。では、何X = yield iですか?そして、関数内の77が外部で発生した場合、どのように5に変換されますか?- 最初の結果文字列がジェネレーター内で起こっていることを反映していないのはなぜですか?
sendとにかく、どういうわけかこれらとyieldステートメントについてコメントできますか?
