In Python, create one of the methods Generator generator is 在函数中使用yield关键字
, the original function becomes a generator.
In other words, if a function contains at least a yield statement (of course, it can also contain other yield or return), then it is a generator.
Understanding the three main points generator:
- It can be seen as a generator
可以停止的函数
. - Between successive calls to the generator, generator of
本地变量和状态会被保存
. - Finally, generator function
再调用generator会引发StopIteration异常
terminates .
Explained below with reference to an example:
In this example, the first two execution print(next(mygen))
after statement calls the Generator continuously, after each call, a local variable and a status generator is saved. After the iterations stop (not yeild), again call generator, iterative abnormal returns.