I. Recursion and iteration
Recursion is calling itself
Iteration is that each iteration is dependent on the last result
Ii. What is an iterator protocol
1, iterator protocol refers to: the object must provide a next method, the execution of the method either returns the next item in the iteration, or causes a Stopiteration exception to terminate the iteration (can only go backward, not forward)
2. An iterative object: An object that implements an iterator protocol (how to: Define an __iter__ () method within an object)
3, the Protocol is a convention, can iterate over the object to implement the iterator protocol, Python's internal tools (such as for loops, Sum,min,max and other functions) are using the iterator protocol to access the object
Third, the powerful for loop mechanism in Python
The nature of the For loop: Loop through all objects, all using the iterator protocol
Radical reform
Many people will think that the nature of the For loop is to follow the iterator protocol to access the object, then the For loop object must be an iterator, yes, so that, for loop can traverse (string, list, tuple, dictionary, collection, file object) that these types of data must be an iterative object? But why do I define a list of a = [1, 2, 3, 4] without the A.next () method, punch the face?
(strings, lists, tuples, dictionaries, collections, file objects) These are not iterative objects, but in the for loop, they call their internal __iter__ method, turn them into an iterative object, and the For loop invokes the __next__ method of an iterative object to fetch the value, And the For loop catches the stopiteration exception to terminate the iteration
Python's Path to growth "fifth article": Python-based iterators and generators