Python で return の代わりに yield を使用するのはどのような場合ですか?

yield ステートメントは関数の実行を一時停止し、呼び出し元に値を送り返しますが、関数が中断したところから再開できるように十分な状態を保持します。関数が再開されると、最後の yield 実行の直後に実行が継続されます。これにより、コードは値を一度に計算してリストのように送り返すのではなく、時間をかけて一連の値を生成できるようになります。

例で見てみましょう:

パイソン




# A Simple Python program to demonstrate working> # of yield> # A generator function that yields 1 for the first time,> # 2 second time and 3 third time> def> simpleGeneratorFun():> > yield> 1> > yield> 2> > yield> 3> # Driver code to check above generator function> for> value> in> simpleGeneratorFun():> > print> (value)>

出力:

1 2 3 

戻る 指定された値を呼び出し元に送り返すのに対し、 収率 一連の値を生成できます。シーケンスを反復処理したいが、シーケンス全体をメモリに保存したくない場合は、yield を使用する必要があります。 Yield は Python で使用されます 発電機 。ジェネレーター関数は通常の関数と同じように定義されますが、値を生成する必要がある場合は常に、return ではなく yield キーワードを使用して生成します。 def の本体に yield が含まれている場合、関数は自動的にジェネレーター関数になります。

パイソン




# A Python program to generate squares from 1> # to 100 using yield and therefore generator> # An infinite generator function that prints> # next square number. It starts with 1> def> nextSquare():> > i> => 1> > # An Infinite loop to generate squares> > while> True> :> > yield> i> *> i> > i> +> => 1> # Next execution resumes> > # from this point> # Driver code to test above generator> # function> for> num> in> nextSquare():> > if> num>>> 100> :> > break> > print> (num)>

出力:

1 4 9 16 25 36 49 64 81 100