Recently see the code in Python to see the yield keyword, and my previous contact with the language does not seem to have, I looked up the meaning of it, probably understand the following:
>>>def creategenerator (): ... mylist= Range (3)... forIinchmylist: ...yieldi*I ...>>> Mygenerator =CreateGenerator () # Create a generator>>> print (mygenerator) # Mygenerator isAnObject!<generatorObjectCreateGenerator at0xb7555c34>>>> forIinchmygenerator: ... print (i)014
1. It's almost the same usage as return, but finally it returns a generator. 2. Understanding yield it is important to know that when you call the function where yield is located, that function is not running, only the object of a generator is returned. 3. When you first call the generator's object in for, it will run the code in your function from the beginning until it hits the yield keyword, and then it returns the first value in the loop. Then every other call will run the loop you wrote in this function one more time, and return the next value, knowing that no value can be returned. The generator can be considered empty if the function runs but does not run to yield. This may be because of the end of the loop, perhaps because you didn't write a safe if/else. Here again comes the generator's problem: The generator and the iterator are similar, but it can only run once, because it does not put the value in memory, but instead runs the generated value directly, so I understand that it should be defined to require a block of code.
>>> Mygenerator = (x*x for x in range (3))
for inch mygenerator: ... Print (i)014 for in mygenerator: ... Print (i)
run again for a for and you won't print anything. Of course, the above understanding comes from: Http://stackoverflow.com/questions/231767/what-does-the-yield-keyword-do-in-python is very good. Very want to vomit trough, I check the mainland of the website of this keyword explanation, the code example gives me around, and take apart to see there is absolutely no need to give so complex code case.
Python yield keyword