Yield keyword

xiaoxiao2021-03-06  14

I have never understood what Yield key is doing. Today, I saw a article called "a generator-based XML Reader", the middle program uses Yield, so I decided to understand it.

Yield is first introduced in python2.2, which must be enable generator to use Yield, change the default of Generator to Enabled in later python2.3. That is to say, you don't have to use from __future__ import generators. The reason for introducing this new key is that the producer function has to introduce the callback function (Callback function as the parameters of the producer function as the parameters of the producer function, which increases the difficulty of writing programs. The efficiency of the program itself.

The Yield key is used in the function body, referred to as generator function. This function and the normal function are different. When the called is called, it is only the parameters of the function, and does not execute the code of any function. Really executed is that the generator iterator is called .Next () method will only start until you encounter Yield (where the local status of the function is all retained, including local variables, internal stack, instruction Pointer, and return the expr_list behind Yield to the iterator called it) or return (RETURN of the generator function cannot return any value, but there is no reason, just Python only makes this implementation), or the end of the function body itself This execution is terminated.

Cute python has some simple introduction: http://www-900.ibm.com/developerWorks/cn/linux/sdk/python/Charm-20/index.shtml

转载请注明原文地址:https://www.9cbs.com/read-49282.html

New Post(0)