yield

Vyzkoušejte a diskutujte se studenty:

def myfunc():
  print('Before first yield.')
  yield 'First yield.'
  print('After first, before second yield.')
  yield 'Second yield.'
  print('After second yield.')

>>> gen = myfunc()
>>> next(gen)
Before first yield.
'First yield.'
>>> next(gen)
After first, before second yield.
'Second yield.'
>>> next(gen)
After second yield.
builtins.StopIteration:
>>> next(gen)
Traceback (most recent call last):
  File "<string>", line 1, in <fragment>
builtins.StopIteration:
>>> 

Volání v cyklu:

for neco in myfunc():
  print('Got from the function:', neco)
  print('---')

vyprodukuje

Before first yield.
Got from the function: First yield.
---
After first, before second yield.
Got from the function: Second yield.
---
After second yield.
>>> 

Výstupy z generátoru lze zamozřejmě posbírat do seznamu:

>>> gen = myfunc()
>>> gen
<generator object myfunc at 0x01081378>
>>> s = list(gen)
Before first yield.
After first, before second yield.
After second yield.
>>> s
['First yield.', 'Second yield.']
>>> 

Pomocí yield lze velmi elegantně vytvořit generátor Fibonacciho řady:

def fibgen():
    a, b = 0, 1
    while 1:
        yield a
        a, b = b, a+b

courses/b4b33rph/tutorialy/python/yield.txt · Last modified: 2018/07/17 13:25 (external edit)