Python in-depth understanding 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:


1 def addlist (alist):
  2 for i in alist:
  3 yield i + 1
  4
  5 alist = [1,2,3,4]
  6 for x in addlist (alist):
  7 print (x)
  8 # The output is:
  9 2
10 3
11 4
12 5
13 [Finished in 0.2s] 


Remove each item from the alist and plug the i + 1 in. Then fetch each item by calling; This is indeed an example of yield application



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


 
 
1 def h():
2     print(‘To be brave‘)
3     yield 5
4 h()


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 before, yield is a statement, but now in 2.5, yield is an expression, such as:



The return value of M = yield 5 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. Look at the principle through the next () statement now, let's see 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:


1 def h ():
  2 print (‘Wen Chuan’)
  3 yield 5
  4 print (‘Fighting!’)
  5 c = h ()
  6 c .__ next __ ()
  7 next (c)
  8 
  9 #The output is:
10 Traceback (most recent call last):
11 File "C: \ Users \ zhangp \ Desktop \ md5.py", line 69, in <module>
12 Wen Chuan
13 Fighting!
14 next (c)
15 StopIteration
16 [Finished in 0.1s with exit code 1] 


After the C.next () call, H () starts 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, it will throw out the exception



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. Therefore, we can be seen as C.next () and C.send (None) are 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 ' figh The result of ting! ' 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. Send (MSG) and Next () return values of Send (MSG) and Next () are return values, their return values are very 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 example above: 1 2 3 4 5 6 7 8 9 def h (): print ' Wen Chuan ', M = Yield 5 # fighting! Print m d = yield print ' We are together! ' c = h () m = C.next () #m obtained yield 5 parameter value 5 D = c.send (' fighting! ') #d obtained Yiel Parameter values for D 12 print ' We'll never forget the date ', M, '. ', D output result: 1 2 Wen Chuan fighting! We'll never forget the date 5. 12 6. The 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 acts the same, in fact internally it is called the throw (generaTorexit). We look at: 1 2 3 4 5 6 7 8 def close (self): Try:self.throw (generatorexit) except (Generatorexit, stopiteration): Pass Else:rai Se runtimeerror ("generator ignored Generatorexit") # Other exceptions is not caught so when we call the close () method, then call next () or send (msg) throws an exception: 1 2 3 4 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 stopiteration call Next () function returns the value after yield, the value of the yield expression is not what is followed by yield, but the value passed in by the Send () function. The passed-in value is assigned to the value of the current yield expression, which is detailed in the following code [Python] View plain copy def f (): print (' start ') a = yield 1 print (a) print (' Middle .... ') b = Yield 2 #2这个值只是迭代值, call next when the value returned by print (b) #传入的参数是给当前yield的, that is, yield 2, because the current function went to yield 2, so the incoming parameter does not give yield 1 print (' Next ') c = Yield 3 print (c) a = f () next (a) next (a) a.send (' msg ') result is: [Python] View plain copy start None Middle .... msg Next [Fin Ished in 0.2s]


Python in-depth understanding yield


Related Article

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.