Learning records of a course , It's more simple


It's a special kind of traversable object , Special lies in

The elements in the iterator can be traversed once

What are the benefits ? The course says

The elements of the iterator are computed ( adopt __next__() Method ) Of , Not always in memory

Turn a traversable object into an iterator

iter Method ,python Built in .
next Method , Get the value of the next element

If you need to implement an iterator class, you need to implement the above two methods ( There's a front and back underline ).


It's a more advanced iterator .

The difference between the two :

  • It's created differently ( How different , I didn't check
  • A generator is an iterator , The former is the evolution of the latter
  • Generators have some special methods that iterators don't have ( What are the details , I didn't check

How it was created :

  • Generator Expressions : Generator expressions are characterized by the use of parentheses , This is the only difference between it and list parsing , The latter uses brackets .
    #g It's a generator
    g = (x**x for x in range(1, 4))
    • Use Python keyword yield Functions written , It's called generator function , The return value of the function is the generator
def fib(n):
current = 0
a = b = 1
while current < n:
yield a
a, b = b, a + b
current += 1 
  • The function above fib Used yield keyword , So it's the generator function ,fib(5) The return value of is a generator
  • yield How to use and return similar , They can only appear inside functions . The difference is ,return Can return valid Python object , and yield The return is a generator . Function encounters return I'm going straight back , And used yield Function of , To yield Returns an element , When you iterate the generator again , From yield Continue later , Until we meet the next one yield Or the function ends and exits .


I feel that my own records of the later courses are a little less than my own thinking , Maybe it's all about applications , I just hope I can record some of my puzzles at that time , Make your records more valuable .