Article From:https://segmentfault.com/q/1010000012136428
Question:
def nums():
    n = 0
    while True:
        n += 1
        yield n

>>> it = nums()
>>> next(it)
    1
>>> next(it)
    2
>>> next(it)
    3    
    
>>> next(nums())
    1
>>> next(nums())
    1 
>>> next(nums())
    1 

Answer 0:

Every time you call nums (), a new generator object is returned. After next is finished, it is destory. And it is always the same

Answer 1:

As you said upstairs, you call each timenums()All run the function again and start yield from 1.

Answer 2:

Give you a chestnut
Suppose num () is an infinite tag library,
it = nums() It’s equivalent to putting a label on the it from the note library.
next(it) The operation has always been it, because it is tagging with nums (), so it has its properties, and next will return to the next value.
next(nums()) It is a tag library, which is equivalent to every time you take a new label, so the first value is returned every time.

Leave a Reply

Your email address will not be published. Required fields are marked *