Study notes (4): Zero-base mastering Python entry to actual combat-deep understanding of iterators and generators

Learn now: https://edu.csdn.net/course/play/26676/399743?utm_source=blogtoedu

1. Iterator

Class special method definition: there are underscores before and after

Determine whether an object is iterable: hasattr(xxx,'__iter__')

The two most important methods of iterators: __iter__, (to determine whether it is iterable), __next__ (to get elements in turn)

 The iterator can optimize the memory well, and it can be called as much as it is used, and it does not need to be transferred to the memory at once.

Use iterator library itertools

 2. Generator

The generator function return value uses yield to return the result (normal function return value uses return to return). Yield return will be suspended at the place of return, waiting for the next call, and continue execution from the place of suspension; the statement after return will not be executed.

Generators are iterable and also iterator objects.

Another parsing method of the generator is similar to that of the list comprehension, replacing the [] of the list with ()

 

Guess you like

Origin blog.csdn.net/weixin_44566432/article/details/107811459