Python 3: send method of generators

后端 未结 4 1180
天涯浪人
天涯浪人 2020-12-12 14:37

I can\'t understand the send method. I understand that it is used to operate the generator. But the syntax is here: generator.send(value).

4条回答
  •  轮回少年
    2020-12-12 15:02

    The most confusing part should be this line X = yield i, specially when you call send() on the generator. Actually the only thing you need to know is:

    in the lexical level: next() is equal to send(None)

    in the interpreter level: X = yield i equals to below lines(ORDER MATTERS):

    yield i
    # won't continue until next() or send() is called
    # and this is also the entry point of next() or send()
    X = the_input_of_send
    

    and, the 2 lines of comment is the exact reason, why we need to call send(None) for the first time, because the generator will return i (yield i) before assign the value to X

提交回复
热议问题