LoginSignup
1
1

Pythonのyieldについて

Last updated at Posted at 2023-07-20

Pythonのyieldとは

  • yieldは与えられた式をgenerator objectに格納して、callerに返します。

  • Pythonではyieldreturnと類似していますが、主要な違いとしてreturnが呼び出された時点で関数の処理を終了するのに対し、yieldは一時停止をし、再開時には引き続き実行されます。

    • Advantages of yield:
      • yieldキーワードを使うと、呼び出し元がオブジェクトを反復するときだけ実行されるので、メモリ効率が高い。
      • 変数の状態が保存されるため、一時停止と再開を同じ時点から行うことができ、時間の節約になる。
    • Disadvantages of yield:
      • ジェネレーターから何度も値が返されるため、コードの流れを理解するのが難しくなることがあります。
      • ジェネレーター関数の呼び出しは適切に処理されなければなりません。
        (https://www.geeksforgeeks.org/python-yield-keyword/)
def fun_generator():
	yield "Hello world!!"
	yield "Geeksforgeeks"


obj = fun_generator()

print(type(obj))

print(next(obj))
print(next(obj))

Output:

<class 'generator'>
Hello world!!
Geeksforgeeks

yieldを使用すると、generator functionとなります。generator functioniteratorsを自動生成し、iterableなobjectとして使用することができるようになります。

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1