The ' iterator ' of Python's three great artifacts

Source: Internet
Author: User
Tags iterable ming

Iterators:

1. Understanding Iterators

Iterators are a way to access the elements of a collection. An iterator is an object that remembers where to traverse. The iterator object is accessed from the first element of the collection until all of the elements have been accessed and finished. Iterators can only move forward without backing back.

How can we determine whether an object is iterative?

2. Can iterate objects

list, tuple, str and other types of data using for...in ... Loop syntax from which the data is taken to be used, which is called an iterative object

3. How to determine whether an object is an object that can be iterated over

You can use Isinstance () to determine whether an object is a Iterable object

 

From collections import iterable# use the Isinstance () function to detect whether an object is an iterative object # list is an iterative object result = Isinstance ([up], iterable) print (result) # tuple is an iterative object result = Isinstance (iterable) print (Result) # string is an iterative object result = Isinstance ("Hello", iterable) Print (Result) # Dictionary is an iterative object result = Isinstance ({"A": Ten, "B": +}, iterable) print (Result) # number is not an iterative object result = isinstance (100 , iterable) print (result) # defines class MyClass (object):    pass# Create Object c1 = MyClass () # object C1 is not an iterative object result = Isinstance (C1, iterable) print (result)

Run results

Truetruetruetruefalsefalse

4. How to convert a non-iterative object to an iterative object:

Before we explore this problem, we need to understand the nature of an iterative object: You can provide us with an intermediate "human" iterator that helps us iterate through it. And the Magic method built into Python __iter__ () method can convert an object to an iterative object, so as long as there is a __iter__ () method in a class, the object of this class instance is an iterative object, and next we will verify the following:

From collections Import iterable# uses the Isinstance () function to detect whether an object is an Iterative object class MyClass (object):    # The essence of an iterative object is whether the class defines __ Iter__ () method    def __iter__ (self):        return SELFC1 = MyClass () # object C1 is not an iterative object result = Isinstance (c1, iterable) print ( Result

Run results

True

5. Create an iterator class

Can the above-created iteration object be accessed with next ()? The result is certainly not, although we define a __iter__ () method in the class, but we do not define a function to iterate over this class, we need to iterate the object with Python's built-in Method __next__ (). Next we will create an iterator and an iterative object to go to s validation:

From collections import Iterablefrom collections Import Iteratorclass studentlist (object): Def __init__ (self): # Create List self.items = List () def addItem (Self,item): # append element to list Self.items.append (item) def __iter __ (self): # Create iterator Object studentiterator = Studentiterator (self.items) # Returns the Iterator object return Studentiter        ator# define iterator Class Studentiterator (object): # define constructor Method # 1) Complete index subscript definition and Initialization # 2) receive list values to traverse def __init__ (self, items):        Self.items = Items Self.current_index = 0 def __iter__ (self): return to self-def __next__ (self): # Determine if the position is legal if Self.current_index < Len (self.items): # Returns the list value according to Current_index item = s  Elf.items[self.current_index] # let subscript +1 Self.current_index + = 1 # returns element content return  Item Else: # Stop Iteration # Unsolicited exception, iterator with no more values (to end of iterator) raise stopiteration# instanced Object stulist = Studentlist () stulist.adDitem ("Xiao Ming") Stulist.additem ("Xiao Hong") stulist.additem ("Xiao Gang") # Check if the object is an iterative result = Isinstance (stulist, iterable) print ( Result) for value in Stulist:print (value) image-20180704185515374

Run results

Xiao Ming Xiao Hong Xiao Gang

Note: If we use next () to access more than the scope of the iteration object will be an error, perhaps you will wonder why we usually iterate over the list, tuples, and other objects can be iterated when there is no such situation, it is because the python inside of the iteration when we traverse the object out of scope will automatically stop, We simply throw an error when we define the iterator class, and we do not have to do so complex processing.

    

  

 

  

The ' iterator ' of Python's three great artifacts

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.