python3.x: Generator Introduction Concept
Any function that uses yield is called a generator; using yield, you can let the function generate a sequence that returns the object type "generator", through which the __next__ () method is called continuously to return the sequence value;
Instance
The generator function only starts executing the statement inside the function when it calls the __next () __ method, for example:
def count (n): while n > 0: yield n # generated value: N N-= 1
With yield, you can have the function generate a sequence that returns an object type of "generator", through which successive calls to the __next__ () method return a sequence value;
c = Count (5) C. __next__ () #python 3.4.3 to use c.__next__ () cannot use C.next ( ) Result: 5 C. __next__
When you call the Count function: C=count (5) does not print "counting" until you call c.__next__ () to actually execute the statement inside. Each time the __next__ () method is called, the Count function runs to the statement yield n
, and the return value of __next__ () is the generated value n
, and when the __next__ () method is called again, The function continues to execute the statement after yield (a friend familiar with Java must know the Thread.yield () method, which is to pause the current thread's run and let other threads execute it), for example:
def count (n): print (" cunting " ) while N & Gt 0: print ( " before yield " ) yield n # generated value: N N-= 1 print (
"
after yield
" )
The preceding code does not print "after yield" when it first calls the __next__ method. If you keep calling the __next__ method, the program will give you an error when it executes to a value that does not have an iteration:
"" inch Stopiteratio
Therefore, the __next__ method is not normally called manually, and a For loop is used:
for in Count (5): print (i)
Example: Implementing the Fibonacci sequence with yield
def Fibonacci (): a=b=1 yield a yield b while True: = b,a+b yield b
Call:
for inch Fibonacci (): if num >: break Print
Yield in return:
as a generator, because each iteration returns a value, so it is not possible to return a value in the generator function, including the none value, or it will throw a "syntaxerror" exception, However, a separate return can appear in the function to indicate the end of the statement.
Read the file continuously through a fixed-length buffer, preventing an example of a memory overflow in a one-time read:
def read_file (path): = 1024x768 with open (path,'r') as F: while True: = f.read (SIZE) if block: yield block Else: return
If you return a specific value in a function, throw the exception directly:
def Test_return (): yield 4 return 0 "<stdin>", line 3 ' return ' with argument inside generator
python3.x: Introduction to Generators