An iterative object iterator in Python

Source: Internet
Author: User

Learning python for some time, in the learning process encountered a lot of difficult to understand things, do a summary, hoping to have some help to other friends.

Completely personal understanding, inevitably wrong, welcome other big God friends criticize correct.

1 iterations

What is an iteration?? We can understand that a container type of data, such as the list [], tuple () and dictionary {}, we can put such a type of data into the for temp in [All-in-one], temp is once the assignment of the data in the back container, and then we get temp to do some want to do of things. Then the for loop automatically helps us to take out the data once and it can be understood that the operation is iterative.

2 Iterative objects

There are some specific data types in Python that can be put into a for-in loop, so that we can say that they are iterative objects.

We can use the Isinstance method to detect whether an object is an object that is not an iteration.

An iterative object can be put into a for-in iteration, or it can be put into list () tuple () to help us quickly generate a data.

On the code!

1  from Import iterable 2 3 Print (Isinstance ([], iterable)  )  #True4print(isinstance ({}, iterable) c14/>) #True5print(Isinstance ((), iterable)  ) #True6  Print(isinstance (1, iterable)  ) #False

From what we can see, lists, tuples, and dictionaries are iterative objects. The integer data is not an iterative object.

What is the essence of an iterative object???? (a face is crazy)

In fact, the inside of an iterative object must implement a method, the __iter__ () method, the function of which is to return an iterator that helps itself iterate. To implement the object of this method, Python considers it to be an iterative object.

What is an iterator??? Don't worry, I'll share it later.

On the code!! Let's look at an iterative object:

1  fromCollectionsImportiterable2 #we create a class of our own to implement the ITER method Python thinks its object is an iterative object.3 classMyiterableobj (object):4     def __iter__(self):5         Pass6 7Demo1 =myiterableobj ()8 Print(Isinstance (Demo1, iterable))#True

As can be seen, we write a class ourselves, which implements the ITER method, even if nothing is done, after creating an object, Judge Python to think that this object is an iterative object.

3 iterators

As we've just said, the ITER method inside an iterative object returns an iterator that helps itself iterate. What is an iterator??

Actually, I don't know either! (hehe laughs and cries) joking ~ ~ ~

In my understanding, an iterator is an object that helps an iterative object take an element out of it. An iterator type object is an iterative object, and for what, let's take a look at the substance.

The essence of the iterator:

Two methods must be implemented inside Iterators: __iter__ () and __next__ ()

The __iter__ () function is to return an iterator that helps us iterate over this type, because we are iterators, so __iter__ () in the iterator returns self

The __next__ () function is: simply to return the value of the next element, like the list, to finish the first element, and then call next to remove the second element. But when you put the list in the For loop, for how do you know that the last element of the list has been exhausted???? (Oh, my God!) Do not know AH!! Whining!!! Don't worry, keep looking down.

In a complex sense, next will do two things: 1 if the current iteration has the next element, return the value of the next element

2 If the current iterator last fetched the last element, it throws an exception (stopiteration), tells some built-in tools such as the For loop, and the iteration is over.

Not very understanding?? Never mind, on the code let's take a look!!

Let's take a look at what Python considers to be an iterator:

 fromCollectionsImportIteratorPrint(Isinstance ([], Iterator))#False It is clear that an iterator object is not an iteratorPrint(Isinstance ([].__iter__(), Iterator))#True This is a ITER method that calls an iterator object to get an iterator object#The iter () method and the next () method are built into Python to pass the object into the same function as __iter__ and __next__.Print(Isinstance (ITER ([]), Iterator))#True#like I said, we implement an iterator ourselves.classMyiterator (object):def __iter__(self):Pass    def __next__(self):PassDemo2=Myiterator ()Print(Isinstance (Demo2, Iterator))#True

See, in our own class object, as long as we have both methods, Python thinks he is an iterator.

Do you remember I said that iterators are iterative objects, because iterators must have a __iter__ method, so it must be an iterative object

Ok! Next, we complement the business logic of the two functions, and look at the two ways the iterator is actually doing??

Let's implement an iterator that passes in an N and iterates over 0 to N. This function is like a range (n) we can do it ourselves!

1 " "2 Next, we implement an iterator capable of completing functions that can be put into a For loop traversal!! Ah, it's so exciting!! 3 The business we're going to implement is: pass in a parameter n, we're going to iterate over the number of 0 to n4 " "5 classNumiterator (object):6     #initialization we receive a parameter n tells us how many iterations to end7     def __init__(self, n):8SELF.N =N9         #We're actually handing I over to the function caller .TenSELF.I =0 One     #The ITER method returns an iterator that is itself an iterator so return to its own A     def __iter__(self): -         return Self -     #Next method to determine if an element is out of bounds if it is not crossed out to throw an exception the     def __next__(self): -         #If there is no bounds, we return the result to the caller iteration, and we record the location of the next iteration -         ifSELF.I <=SELF.N: -res =self.i +SELF.I + = 1 -             returnRes +         #go to else note I has exceeded n iterations out of bounds and throws an exception to tell the For loop iteration to end A         Else: at             #If this exception is not thrown, the for loop does not know when to stop the iteration and will not stop calling next into a dead loop -             Raisestopiteration -  - #an iterator object for the first 3 natural number -Demo3 = Numiterator (3) - #as I said before, we can call Python's built-in next method to get the elements of an iterator in Print(Next (DEMO3))#0 - Print(Next (DEMO3))#1 to Print(Next (DEMO3))#2 + Print(Next (DEMO3))#3 - #print (Next (DEMO3)) # This time again the call throws an exception because it's out of bounds!  the  * #Also, the iterators we write ourselves can be put into a for loop. $Demo4 = Numiterator (10)Panax Notoginseng  forNuminchDemo4: -     Print(num) the #we found that it would print out from 0 to 10 and then the for loop would stop.

After reading the above code, let me explain the actual nature of the FOR loop:

For not knowing what we put in the back of an iterator or iterator, he would call the ITER method to get an iterator, and then call the next method to fetch the value, and then provide it to us.

Ok!! Here, you can iterate over the object, the knowledge of the iterator is shared with everyone.

Do not know the small partners have not understood, hope to some do not understand these deep-seated things of the students have some help!!

Welcome everyone to criticize ~ ~ ~ ~ ~ Thank you for your reference!

I am a confused Lin old Cold ~

An iterative object iterator in Python

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.