Elegant Python-yield Concise Tutorial

Source: Internet
Author: User

Found that there are many people do not understand yield, foggy, and then try to express in words.

as long as the function contains a yield statement, it returns a generatorSo instead of seeing it as a function definition, we think of it as Generator Definition. function with returnReturned, and the generator yieldReturn.
Next comes the act of yield.

Like what

def html ():    yield ' header ' for    I in range (5):        yield i-    yield ' footer ' H = HTML () #此时h变量就是一个生成器. For x in H: #遍历 Generator    Print X
How do you understand this function?
Use "yield elimination Technology", use a result variable to collect the yield and return it.
Then converted into

def html ():    ret = []    ret.append (' header ') for    I in range (5):        ret.append (i)    ret.append (' footer ')    return RET
As you can see, the yield statement is gone and everything is in the RET sequence.

and powerful magic of the generatorIs that it is deferred execution, it executes the code when needed, it "remembers" where the yield is executed, and when it gets the next result, it goes down from the last yield position.
So the generator is relative to the list, it saves only one current result at a time, saves memory, the disadvantage is that the subscript index cannot be used, and the traversal is gone. Another benefit is that you can generate infinite sequences, such as cycle.

It is important to note that when we call a function, it does not start executing the function body code, but returns a generator.
Like what
Def A ():    print ' hehe '    yield 1    yield 2
When we are a (), it does not print ' hehe ', but only when we traverse it, it begins to execute, from the first line of code in the function body to the first yield, and then continues to execute the code to the next yield, so go on.



Elegant Python-yield Concise Tutorial

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.