Deep understanding of yield

Source: Internet
Author: User
Yield of the English word meaning is production, just contact with Python is very confused, has not understood the use of yield.

It's just a rough idea. Yield can be used to return value plug data for a function, such as the following example:

def addlist (alist): For    i in alist:        yield i + 1

Remove each item from the alist and plug the i + 1 in. Each entry is then fetched by calling:

Alist = [1, 2, 3, 4]for x in Addlist (alist):    print X,

This is indeed an example of yield application

1. Functions that contain yield

If you see a function that contains yield, which means that the function is already a generator, its execution will be a lot different from other normal functions. For example, the following simple function:

def h ():    print ' to be brave '    yield 5h ()

As you can see, after calling H (), the print statement is not executed! This is yield, so how do you get the print statement to execute? This is the question to be discussed later, through the discussion and study later, we will understand how yield works.

2. Yield is an expression

Python2.5 Previously, yield was a statement, but now in 2.5, yield is an expression, such as:

m = Yield 5

The return value of the expression (yield 5) is assigned to M, so that M = 5 is wrong. So how do you get the return value (yield 5)? You need to use the Send (msg) method that is described later.

3. See the principle through the next () statement

Now, let's reveal how yield works. We know that the H () above is called and is not executed because it has a yield expression, so we let it execute through the next () statement. The next () Statement resumes generator execution, and until the next yield expression. Like what:

def h ():    print ' Wen Chuan '    yield 5    print ' fighting! ' c = h () C.next ()

After the C.next () call, H () begins execution until yield 5 is encountered, so the output is:

Wen Chuan

When we call C.next () again, we continue execution until we find the next yield expression. Because there is no yield at the back, the exception is thrown:

Wen chuanfighting! Traceback (most recent):  File "/home/evergreen/codes/yidld.py", line one, in 
 
  
   
      c.next () Stopiteration
 
  

4. Send (MSG) and Next ()

Once we see how next () is going to make the function that contains yield, let's look at another very important function, send (msg). In fact, next () and send () function in a certain sense is similar, the difference is that send () can pass the value of the yield expression in, and next () cannot pass a specific value, can only pass the none in. So we can be seen as

C.next () and C.send (None) Act the same.

Take a look at this example:

def h ():    print ' Wen Chuan ',    m = yield 5  # fighting!    Print m    d = yield    print ' We are together! ' c = h () c.next ()  #相当于c. Send (None) c.send (' fighting! ')  # (yield 5) expression is given ' fighting! '

The result of the output is:

Wen Chuan fighting!

Note that the first call, use the next () statement or send (None), you cannot use Send to send a value other than None, otherwise it will be wrong, because there is no yield statement to receive this value.

5. The return value of Send (msg) and Next ()

Send (MSG) and Next () have return values, their return values are special and return the parameters of the next yield expression. Yield 5, for example, returns 5. Do you understand something here? In the first example of this article, traversing Generator with the for I in Alist actually calls alist each time. Next (), and every time alist. The return value of Next () is exactly the yield parameter, which is what we begin to think is being pressed in. Let's continue with the above example:

def h ():    print ' Wen Chuan ',    m = yield 5  # fighting!    Print m    d = yield    print ' We are together! ' c = h () m = C.next ()  #m obtained the parameter value of yield 5 5d = c.send (' fighting! ')  #d obtained the yield 12 parameter value 12print ' We'll never forget the date ', M, '. ', D

Output Result:

Wen Chuan fighting! We'll never forget the date 5. 12

6. Throw () and close () interrupt Generator

Interrupt generator is a very flexible technique that can be used to terminate generator by throwing a generatorexit exception. The Close () method works the same, but inside it is called throw (generatorexit). We look at:

def close (self):    try:        self.throw (generatorexit)    except (Generatorexit, stopiteration):        Pass    else:        raise RuntimeError ("generator ignored Generatorexit") # Other exceptions is not caught

Therefore, when we call the close () method and then call next () or send (msg), an exception is thrown:

Traceback (most recent call last):  File "/home/evergreen/codes/yidld.py", line +, in 
 
  
   
      d = c.send (' fighting! ')  #d obtained the parameter value of yield 12 12StopIteration
 
  
  • Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.