The yield use method in python

  • 2020-04-02 13:23:45
  • OfStack

Today, while looking at other colleagues' code, I found an unused python keyword: yield

          First asked a colleague, he said a few words, there is a vague impression, just vague. Then oneself search data to see. After looking at it for a long time, it gradually became clear. But in the working mechanism and application is still a bit confused. Well, just write down the initial impressions of the contact.

          Yield is simply a Generator. A generator is a function that remembers its position in the body of the function when it last returned. The second (or NTH) call to the generator function jumps into the middle of the function, leaving all local variables unchanged from the last call.

          You see that a function contains yield, which means that the function is already a Generator and that it will perform a lot differently from other normal functions.

          You may see that this is still a bit confusing, but let's take a look at some examples:


      def test( data_list ):
            for x in data_list:
                 yield x + 1
      data = [1,2,3,4]
      for y in test( data ):
           print y

          Then the output result is:

          2             3             4               5

          Another usage:

          Handle = test (data)

          Handle. Next ()         The output   2

          Handle. Next ()         The output   3

          Handle. Next ()         The output   4

          Handle. Next ()         The output   5

          Handle. Next ()         May be an error

          This is just a first impression of yield.


Related articles: