test environment
win10
python 3.5
yield function introduction
Simply put, the role of a yield is to turn a function into a generator. A function with a yield is no longer an ordinary function; the Python interpreter treats it as a generator.
Code Demo
Example 1: Generate the first N numbers of the Fibonacci series.
#!/usr/bin/env python # -*- coding:utf-8 -*- __author__ = 'shouke' def fab(max): n, a, b = 0, 0, 1 result = [] while n < max: (b) a, b = b, a + b n = n + 1 return result for n in fab(5): print(n)
Although the above code can satisfy the demand, there is a problem: the memory occupied by this function will increase with the increase of the parameter max, if you want to control the memory occupation, it is better not to use List
Improving the use of yield
def fab(max): n, a, b = 0, 0, 1 while n < max: yield b # Use yield a, b = b, a + b n = n + 1 for n in fab(5): print(n)
Example 2: Reading a file in binary mode and generating a copy of the file
#!/usr/bin/env python # -*- coding:utf-8 -*- __author__ = 'shouke' def read_file(fpath): BLOCK_SIZE = 1024 with open(fpath, 'rb') as f: while True: block = (BLOCK_SIZE) if block: yield block else: return with open('D:\Downloads\\channels-2.1.', 'wb') as f: for data in read_file('D:\Downloads\\channels-2.1.'): (data)
This is the whole content of this article.