「Python3.9」ジェネレータにsendメソッドを使用するサンプル

環境
Python 3.9.13
Windows 11 Pro 21H2 64bit
PyCharm 2022.2.1 (Community Edition)

構文
def 関数名()
yield “文字列"
変数名 = 関数名()
変数名.send(文字列
関数内にキーワードのyieldを記述します。
yield文は値を返します。
関数を呼ぶ側は、next関数で呼び出します。
send関数を使用すると関数に値をセットすることができます。
値を返したところを記憶していて次回は続きから行います。

使用例

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
# coding: utf-8
#関数の定義
def funA(x):
for a in range(10):
b = yield ('info',x)
if b is not None:
x = b
res = funA("study")
# 引数の値がセットされて表示され
print(next(res))
# sendメソッドを利用
res.send("skill")
print(next(res))
print(next(res))
# coding: utf-8 #関数の定義 def funA(x): for a in range(10): b = yield ('info',x) if b is not None: x = b res = funA("study") # 引数の値がセットされて表示され print(next(res)) # sendメソッドを利用 res.send("skill") print(next(res)) print(next(res))
# coding: utf-8
#関数の定義
def funA(x):
      for a in range(10):
            b = yield ('info',x)
            if b is not None:
                  x = b

res = funA("study")
# 引数の値がセットされて表示され
print(next(res))

# sendメソッドを利用
res.send("skill")

print(next(res))
print(next(res))

実行結果

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
('info', 'study')
('info', 'skill')
('info', 'skill')
('info', 'study') ('info', 'skill') ('info', 'skill')
('info', 'study')
('info', 'skill')
('info', 'skill')

 

Python

Posted by arkgame