程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Detailed explanation of the usage of yield in Python -- the simplest and clearest explanation (Reprint)

編輯:Python

Reprinted from :https://blog.csdn.net/mieleizhi0522/article/details/82142856

First, I want to make complaints about it , In the process of looking at the program, I met yield This keyword , Then when Baidu , I found that there is no one that can simply let me understand , It's true TM Everything is right , What parameters , What passed , He also keeps saying that his tutorial is the simplest , The easiest to understand , I just want to ask if I have considered the feelings of readers .

Next is the main topic :

First , If you are not right yield Have a preliminary understanding , Then you take yield regard as “return”, This is intuitive , First of all, it is a return, ordinary return What does that mean? , Is to return a value in the program , After returning, the program will no longer run down . regard as return Then think of it as a generator (generator) Part of ( belt yield The function of is the real iterator ), Okay , If you don't understand this , Then first yield regard as return, Then look directly at the following program , You will understand yield The whole meaning of : 

def foo():
print("starting...")
while True:
res = yield 4
print("res:",res)
g = foo()
print(next(g))
print("*"*20)
print(next(g))

Just a few lines of code will let you know what is yield, The output of the code :

starting...
4
********************
res: None
4

I'll explain the code sequence directly , Equivalent to code single step debugging :

1. After the program starts executing , because foo In function yield keyword , therefore foo Functions don't really execute , It's a generator first g( Equivalent to an object )

2. Until the call next Method ,foo The function officially starts executing , Execute first foo Function print Method , Then enter while loop

3. Program encounter yield keyword , And then put yield Think about it return,return One. 4 after , The program to stop , There is no execution assigned to res operation , here next(g) Statement execution complete , So the first two lines of output ( The first is while above print Result , The second is return The result ) Is to perform print(next(g)) Result ,

4. Program execution print("*"*20), Output 20 individual *

5. Start again with the following print(next(g)), It's about the same time as the one above , But here's the difference , This time is from the next Where the program stops , That is to carry out res Assignment of , Pay attention to , At this time, there is no value on the right side of the assignment operation ( Because that was return I'm out , There is no parameter passed to the left side of the assignment operation ), So at this point res The assignment is None, So the next output is res:None,

6. The program will continue in while Internal execution , Another encounter with yield, It's the same time return Out 4, Then the program stops ,print Function output 4 Is this time return Out of 4.

Here you may understand yield and return The relationship and difference between , belt yield The function of is a generator , Not a function , This generator has a function that is next function ,next Equivalent to “ next step ” Which number is generated , This time next The place to start is next to the last time next Where to stop , So call next When , Generators don't come from foo Function start execution , It's just where the last stop started , And then meet yield after ,return Figure out the number to generate , This step is over .

****************************************************************************************************************************************
 

def foo():
print("starting...")
while True:
res = yield 4
print("res:",res)
g = foo()
print(next(g))
print("*"*20)
print(g.send(7))

  Look at another example of this generator send Examples of functions , This example replaces the last line of the above example , Output results :

starting...
4
********************
res: 7
4

Let's talk about it in general send The concept of function : At this time, you should pay attention to the purple words above , And the one above res Why is the value of None, This has become 7, Why on earth , This is because ,send Send a parameter to res Of , Because it says ,return When , Not yet 4 Assign a value to res, The next time I execute it, I have to continue the assignment operation , It has to be assigned as None 了 , And if used send Words , At the beginning of execution , First, then the last time (return 4 after ) perform , The first 7 Assigned to res, And then execute next The role of , Meet the next yield,return After the result .

5. Program execution g.send(7), The program will start from yield The keyword line continues to run down ,send Will be able to 7 This value is assigned to res Variable

6. because send Method contains next() Method , So the program will continue to run down print Method , Then go back to while loop

7. Program execution encounters again yield keyword ,yield Will return the following value after , The program is suspended again , Until it's called again next Method or send Method .

It's over , The way , Why use this generator , Because if you use List Words , It will take up more space , For example, take 0,1,2,3,4,5,6............1000

You might be like this :

for n in range(1000):
a=n

This is the time range(1000) By default, it will generate a containing 1000 The number of list 了 , So it takes up a lot of memory .

At this time, you can use the yield Combine them into generators for implementation , It can also be used. xrange(1000) This generator implements

yield Combine :

def foo(num):
print("starting...")
while num<10:
num=num+1
yield num
for n in foo(0):
print(n)

Output :

starting...
1
2
3
4
5
6
7
8
9
10

xrange(1000):

for n in xrange(1000):
a=n

It should be noted that python3 There was no more xrange() 了 , stay python3 in ,range() Namely xrange() 了 , You can python3 View in range() The type of , It's already a <class 'range'> 了 , Instead of a list 了 , After all, this needs to be optimized . 

————————————————
Copyright notice : This paper is about CSDN Blogger 「 Feng Shuanglang 」 The original article of , follow CC 4.0 BY-SA Copyright agreement , For reprint, please attach the original source link and this statement .
Link to the original text :https://blog.csdn.net/mieleizhi0522/article/details/82142856/


  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved