Python Learning Diary (5) Simple knowledge of iterators, generators, adorners, context managers

Source: Internet
Author: User

Iterators

An iterator is simply a container object that implements the iterator protocol. It is based on the following two methods.

__ next __: Returns the next element of the container.

__ iter __: Returns the iterator itself.

In fact, iterators represent the underlying concepts and features of the program, and in a program you don't have to use iterators, but understanding iterators is helpful in understanding a common feature such as generators.

Learning iterators, I have basically 2 examples to understand the characteristics of iterators. (PS: I found that I remember the notes are not very detailed, so this piece of the record in detail ...) Otherwise I sometimes some point I look at the time to think about it, vomiting blood, really no spirituality ... )

Okay, on the code:

A = ITER ([11,22,33])print (Next (a)) print (next (a)) print ( Next (a))-------------------------112233 in 0.2s]

Here, I created a very primitive iterator, using the iter () function , which receives a list as a parameter in the above code and assigns a value to the A variable.

So at this point, a is an iterator. Of course, the iterator created at this point is very rudimentary, like I'm going to build a plane, and you're folding me up with paper. However, the characteristics of the plane is still some, can be regarded as a plane, but a paper plane.

Iterators use: By using the function next () , the next () function parameter receives an iterator, and at each execution time, the value in the iterator is called and returned.

Simple to understand: next () function, like game login, game is like an iterator, no login you can not play the game, so, without next () This thing you can not use the iterator, you want to use the iterator, you need to use next () This method to tune, Next () This method has a feature, from the beginning of the tune, Each time you tune one.

So why is it that the iterator we created with ITER () is a paper plane?

Look at the code thinking 2 questions:

1, each call is called sequentially, the above code is called just a list, if you call the last value in the list, continue to call, what happens?

A = ITER ([11,22,33])print (Next (a)) print (next (a)) print ( Next (a))print(Next (a))------------------------- in 0.2s with exit code 1]

As you can see, there are only 3 values in the iterator, and I called 4 times, so I returned a stopiteration exception when I called the fourth time. This is good, the exception represents the end of the iteration, we can use the exception to do something.

2, why the paper plane, this iterator has a very bad point, that is, the number of iterations is not what we want, if we want to iterate 100 times, will not write a list of 100 elements? Of course, you can say I can use range () to solve this problem.

A = ITER (range (4)) print (next(a)) print (next (a)) print ( Next (a))print-------------------------------0123 in 0.2s]

However, in practice, the problem of triggering an exception is not resolved. And each iteration requires next () to be done manually, so let's do a real iterator.

classcountdown ():def __init__(self,step): Self.step=Stepdef __next__(self):ifSelf.step <=0:Raisestopiteration Self.step= Self.step-1returnSelf.stepdef __iter__(self):returnselfff= Countdown (5) forIinchFF:Print(i)-------------------------------------43210[finishedinch0.2S]

__ next __: Returns the next element of the container.

__ iter __: Returns the iterator itself.

This class is very clear, receiving iterations, and each iteration minus 1, triggering an exception to stop the iteration. In fact, iterations are just a concept, and iterators provide a specialized approach, not the only iterative action in a python program!

Generator

The builder is an elegant way to make it easy and efficient to write function code that returns a sequence of elements.

In fact, we used the method: Range ()

 for  in range:    print(i)

It also generates a list for us to traverse, and in Python3, the essence is also the generator.

Of course, we can also write a list generator ourselves, without using range ()

defMaker (num): a=0 whiletrue:b=a A= A + 1Num= Num-1yieldbifNum <=0: BreakFF= Maker (10) A= [I forIinchMaker (10)]b= [x forXinchRange (10)]Print(a)Print(b)--------------------------------------------[0,1, 2, 3, 4, 5, 6, 7, 8, 9][0,1, 2, 3, 4, 5, 6, 7, 8, 9][finishedinch0.2S]

Look, we've written ourselves a generator method maker (), which takes a parameter to represent the number of generated lists, the same way as the range () function. (at least the call seems to be Yes)

The: Yield statement in the code, which represents the pause generator, returns the result. Isn't it a bit like return? Can think of, there is a difference, one is a pause, return after the execution of the following code, return returned after the execution is not.

In fact, the generator can perform complex build processes, but it depends on what you need to achieve.

Python Learning Diary (5) Simple knowledge of iterators, generators, adorners, context managers

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.