投稿

2月 23, 2021の投稿を表示しています

help("yield")

>>> help("yield") The "yield" statement ********************* yield_stmt ::= yield_expression A "yield" statement is semantically equivalent to a yield expression. The yield statement can be used to omit the parentheses that would otherwise be required in the equivalent yield expression statement. For example, the yield statements yield yield from are equivalent to the yield expression statements (yield ) (yield from ) Yield expressions and statements are only used when defining a *generator* function, and are only used in the body of the generator function. Using yield in a function definition is sufficient to cause that definition to create a generator function instead of a normal function. For full details of "yield" semantics, refer to the Yield expressions section. >>>

yield sample progaram

def myfunc(): yield 'one' yield 'two' yield 'three' yield 12345 print("test myfunc") for s in myfunc(): print(s) print("test myfunc by next") gene = myfunc() print(next(gene)) print(next(gene)) print(next(gene)) def myfunc2(x:int): # 0からxまでの値を2倍して返す for z in range(x): yield z*2 print("test myfunc2") for i in myfunc2(5): print(i) ===== RESTART: C:/python/yieldTest20210224.py === test myfunc one two three 12345 test myfunc by next one two three test myfunc2 0 2 4 6 8 >>>

Why do we use yield in Python?

We should use yield when we want to iterate over a sequence but don't want to store the entire sequence in memory. yield is used in Python generators. A generator function is defined like a normal function, but whenever it needs to generate a value, it does so with the yield keyword rather than return.