Python Builder and send usage explained

Source: Internet
Author: User

-Generator

When we call a normal Python function, we typically start with the first line of the function, ending with a return statement, an exception, or the end of the function (which can be considered an implicit return of none). Once the function returns control to the caller, it means that it is all over. All the work done in the function and the data saved in the local variables will be lost. When you call this function again, everything will be created from scratch.
This is a very standard process for the functions discussed in computer programming. Such a function can only return a value, but sometimes it can be helpful to create a function that produces a sequence. To do this, this function needs to be able to "save its own work".
As I said, being able to "produce a sequence" is because our function does not return as usual. Return implies that the function is returning control of the execution code to the place where the function was called. The implied meaning of "yield" is that the transfer of control is temporary and voluntary, and our function will regain control in the future.

The initial introduction was to make it easier for programmers to write code to produce a sequence of values

▲. Sequence of generated values

handling an infinite sequence ==> consuming too much memory ==> encountering a problem: the function has only one chance to return the result, so all results must be returned at once ==> if Get_primes can simply return the next value, Instead of returning all values at once

The definition of a generator function is much like a normal function, except that it uses the yield keyword instead of return when it wants to generate a value. If the body of a def contains yield, the function will automatically become a generator (even if it contains a return). In addition to the above, there is no extra step in creating a generator.

A generator is a special kind of iterator. As an iterator, the generator must define some methods, one of which is next (). As with iterators, we can use the next () function to get the next value.

The while loop is used to ensure that the generator function never executes to the end of the function.

PEP 342 adds a new feature

Send a value to the generator by using the Send method. other = yield Foo This means, "return the value of Foo, this value is returned to the caller, and the value of other is also set to that value

    def get_primes(number):        while True:            if is_prime(number):                number = yield number            number += 1    通过这种方式,我们可以在每次执行yield的时候为number设置不同的值。现在我们可以补齐print_successive_primes中缺少的那部分代码:    def print_successive_primes(iterations, base=10):        prime_generator = get_primes(base)        prime_generator.send(None)        for power in range(iterations):            print(prime_generator.send(base ** power))
-Understanding Send
    def Get_allprimes(num):        while True:            if prime_num(num):                print(‘num‘,num)                other = yield num                print(‘other‘,other)            num += 1        gene = Get_allprimes(34)    gene.send(None)    gene.send(61)    output:    >>>num 37    >>>other 61    >>>num 41
★ Focus: look at that xx = yield yy .

Summary: The function of Send () is to assign XX to the value sent (the Send parameter), and then let the generator execute to the next yield:

Use of Send (params) requires a distinction. Note: If the generator does not start, you must start the generator before using Send (), and the startup method can be Generator.next () or Generator.send (None) to the first yield. You can then use Send ( params) constantly passing in values. If it is started, the function of send (params) is to assign XX to the value sent (the Send parameter), and then let the generator execute to the next yield:

Why you need Send (None) is also very well understood, because the generator has not gone to the first yield statement, if we happen to a real value, then no one to "receive" it. Once the generator is started, the object is accepted (that is, the left value XX on the left of the = sign is accepted), and then you can use Send (params) to continuously pass in the value.

▲ Note that every time the send () runs to the yield statement, but the assignment does not execute, only the return value, which is the equivalent of returning, exits the function, so the assignment after the return value is not executed.

In my opinion, the function of Send () is on the basis of next (), there is a function to assign the value of XX. If the second gene.send (61) starts from the last stop yield, so that the other assignment is 61, and then executes to the next yield place ===> can be seen when the Send method parameter is none, it is completely equivalent to the next method

More (Give a more detailed explanation to people who have not yet understood):
    • Send (none) after the send (int class parameter), and then the Send (none) effect is what?
  def Gene (): #生成器函数 print ("OK") x = + print (x) First = yield        # #这里就是send函数的关键 # The value passed by send is actually the left value of the = number assignment print (first) second = yield x # Try the second breakpoint here                   Print (second) z = ' third ' third = yield Z print (third) inst = Gene () #创建生成器对象 output1 = inst.send (None) #启动生成器, run to the first yield print (OUTPUT1) #这边的output1获得的是yield的返 Output2 = Inst.send (output2) output3 = inst.send (None) output: >>>ok >>&G t;100 ==>print (x) >>>50 ==>print (OUTPUT1) >>>30 ==>send (30) First is assigned a value of 30 Post print (first) >>>100 ==>print (output2) ==>output = x==100 >>>none ==>send (None) s Econd is assigned a value of None,print (second) ==>none  
Each send (params) runs to the yield statement, but the assignment is not executed and only the return value is returned. The assignment assigns a value of XX to the params at the next send (params), and executes the following only the return value:

OUTPUT1 Accept the return value:

Execute Send (params):

Assign the Passvalue to the params:

Accept the return value of the second yield to run to:

Reference Blog Builder

Python Builder and send usage explained

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.