How can you learn Python without knowing yield?

introduction

You may have heard that a function with a yield is called a generator in Python, or you haven't paid attention to it. There is also a yield in Python. If you know yield in Python, do you know what a generator is?

 

The concept of yield

To understand the generator concept of yield, first show the concept of yield with a common programming topic.

How to generate Fibonacci sequence

The Fibonacci sequence is a very simple recursive sequence. Except for the first and second numbers, any number can be obtained by adding the first two numbers. Using a computer program to output the first N numbers of the Fibonacci sequence is a very simple problem. Some Python-based friends can easily write the following functions:

 

Version 1: Simply output the first N numbers of the Fibonacci sequence

def createNum(count): 
    n, a, b = 0, 0, 1 
    while n < count: 
        print b 
        a, b = b, a + b 
        n = n + 1
createNum(5)

Executing the above code, we can get the following output:

1 
1 
2 
3 
5

There is no problem with the output result, but the writing method in version 1 is to print the numbers directly in the createNum function with print, which will cause the function's reusability to be poor, because the createNum function returns None, and other functions cannot get the number sequence generated by the function.

To improve the reusability of the createNum function, it is best not to print out the number sequence directly, but to return a List. The following is the second version of the rewritten createNum function:

 

Version 2: Output the top N numbers of the Fibonacci sequence

def createNum(count): 
    n, a, b = 0, 0, 1 
    L = [] 
    while n < count: 
        L.append(b) 
        a, b = b, a + b 
        n = n + 1 
    return L
 
for n in createNum(5): 
    print n

The results of the List returned by the createNum function in this version are as follows:

1 
1 
2 
3 
5

The rewritten createNum function can meet the requirements of reusability by returning List, but at the same time there will be an obvious problem: the memory occupied by the function in operation will increase with the increase of the parameter count, if To control memory usage, it is best not to use List to store intermediate results, but to iterate through iterable objects. In each iteration, the next value is returned, so: the memory space is very small. Because it returns an iterable object directly.

 

Version 3: Use yield to output the first N numbers of the Fibonacci sequence

def createNum(count): 
    n, a, b = 0, 0, 1 
    while n < count: 
        yield b      # 使用 yield
        # print(b) 
        a, b = b, a + b 
        n = n + 1
 
for n in createNum(5): 
    print n

You can also manually call the next() method of createNum(5) (because createNum(5) is a generator object, which has a next() method), so that we can see the execution flow of createNum more clearly:

 

Version 4: Execution Process

def createNum(count): 
    n, a, b = 0, 0, 1 
    while n < count: 
        yield b      # 使用 yield
        # print(b) 
        a, b = b, a + b 
        n = n + 1
 

#使用for循环来执行createNum()函数,它返回一个迭代值,下次迭代从yield语句的下一条语句继续执行
<!--for n in createNum(5): 
    print n-->

#使用next方法来执行createNum()函数,generator(生成器)对象具有next()方法
num = createNum(5)
print(next(num))
print(next(num))
print(next(num))
print(next(num))
print(next(num))
print(next(num))

Run the above code, the result output is as follows:

1
1
2
3
5
Traceback (most recent call last): 
 File "<stdin>", line 1, in <module> 
StopIteration

From the output result, it can be found that a StopIteration exception is thrown when the sixth print(next(num)) is executed, because the function has ended when the fifth print(next(num)) is executed, and then the sixth is executed. When print(next(num)), the generator automatically throws StopIteration exception, indicating that the iteration is complete. In the for loop, there is no need to handle StopIteration exceptions, and the loop will end normally.

 

 

The role of yield

Simply put, the function of yield is to turn a function into a generator. The function with yield is no longer an ordinary function. The Python interpreter will treat it as a generator. Calling createNum(5) will not execute the createNum function. Instead, it returns an iterable object!

 

When the for loop is executed, the code inside the createNum function will be executed each time the loop is executed. When it reaches yield b, the createNum function will return an iteration value. At the next iteration, the code will continue to execute from the next statement of yield b, and the function The local variable looks exactly the same as before the last interrupt execution, so the function continues execution until it encounters yield again.

 

 

Yield usage scenarios

  • Iteratively generate data (producer, the advantage is more obvious when the amount of data is huge, it does not take up a lot of memory)

  • Receive data (consumer)

  • Interruption (cooperative task)

 

to sum up

A function with yield is a generator. It is different from ordinary functions. Generating a generator looks like a function call, but will not execute any function code until next() is called (in the for loop, next() will be called automatically. )) to start execution. Although the execution flow is still executed according to the flow of the function, it will be interrupted every time a yield statement is executed, and an iteration value will be returned. The next execution will continue from the next statement of the yield. It seems as if a function is interrupted by yield several times during normal execution, and each interruption will return the current iteration value through yield.

The benefit of yield is obvious. Rewriting a function into a generator gains iterative ability. Compared with using a class instance to save the state to calculate the next next() value, not only the code is concise, but the execution flow is extremely clear.

Welcome to pay attention to [The Way of Infinite Testing] public account , reply [Receive Resources]
Python programming learning resources dry goods,
Python+Appium framework APP UI automation,
Python+Selenium framework Web UI automation,
Python+Unittest framework API automation,

Resources and codes are sent for free~
There is a QR code of the official account at the bottom of the article, you can just scan it on WeChat and follow it.

Remarks: My personal public account has been officially opened, dedicated to the sharing of test technology, including: big data testing, functional testing, test development, API interface automation, test operation and maintenance, UI automation testing, etc., WeChat search public account: "Infinite The Way of Testing", or scan the QR code below:

 Add attention and let us grow together!

Guess you like

Origin blog.csdn.net/weixin_41754309/article/details/113758928