To understand generator and yield, we can debug the code below.
put break point at line 5,6 and 10
- when the code is executed, line 9, it calls fibon(10) to get x
- the fibon function is executed to line 5, yield a, it suspends the process of fibon and return to the main process, x gets the value of a.
- Then line 10, print(x), we can have code here which consumes system resources here.
- Once it is done, it goes back to line 9, for x in fibon(10), ask for next value from fibon function
- It goes to line 6, the place where it is suspended, run the calculation, continue the iteration to line 4, 5 yield again, it will pop the calculated value to the main process line 10 again.
to send the value into the function
http://book.pythontips.com/en/latest/generators.html
http://kissg.me/2016/04/09/python-generator-yield/
No comments:
Post a Comment