Python base (15) - iterators and generators

The difference between recursive and iterative

Recursion is a process of waiting for internal pointer, the need has been nested result, the iterative process is traversed, after the foregoing process may be carried out at a without waiting

Iterator protocol and mechanisms for loop

Next object must provide a means for the implementation of this method either returns the next iteration, or to cause a stopiteration abnormal termination of the iteration (only backward, not forward)

Iterables, iterator protocol is to achieve the object, an object defined inside the __iter a __ () method

Protocol is a convention, iterables implement a protocol, it can be accessed by the iterator protocol, Python internal tool for, sum min max function

But the strings, lists, tuples, a collection of file objects these are not iterable, but under the influence of the for loop, for __iter__ method called them inside and put them into a iterables

= A ' Hello ' 
b = A. the __iter__ () # generated iterator object address of b 
Print (b. __next__ ()) # value until the error

for loop actually implements the __iter __ () method generates an iterator object, then an error message and returns until the next step is a complete process

For such a sequence, for dictionaries and documents is true, unified generated iterator loop

Therefore, all internal object can have a loop for the __iter __ () method

for i in file: it reads files for, document generation iterators are read line by line, in front of the finish line memory to reclaim lost, do not take up memory

next () built-in function is actually implemented inside the __next object __ () method, the same effect

 

Guess you like

Origin www.cnblogs.com/dayouge/p/11100025.html