Python iterators and generators

Source: Internet
Author: User

First of all, the iterator, for string, list, dict, tuple and other such container objects, using for loop traversal is very convenient, in the background for statement on the container object object called the iteration () function, which is a python built-in function, ITER () returns an iterator object that defines the next () method, which accesses the container element individually in the container, and next () is also a python built-in function. In the absence of subsequent elements, the call to next () throws a Stopiteration exception

These are all Python-brought container objects, they all implement the corresponding iterator method, the custom class traversal how to implement, the method is: To this class AClass, implement the __iter__ (self) method, so that it returns a with the __next__ (self) The object of the method is available. If you have exactly defined the __next (self) method in AClass, you can only return self in __iter__.

__iter__ () and Next () methods

These two methods are the most basic method of iterators, one to get the iterator object, and one to get the next element in the container.

Class MyRange (object):
def __init__ (self,n):
Self.idx=0
Self.n=n
def __iter__ (self):
return self

Def next (self):
If SELF.IDX<SELF.N:
val = Self.idx
Self.idx +=1
Return Val
Else
Raise Stopiteration ()

MyRange = MyRange (3)
For I in MyRange:
Print I

MyRange This object is an iterative object, and it is itself an iterator object.

Generator

In Python, the use of generators makes it easy to support iterator protocols. Generators are generated through the generator function, which can be defined by a regular DEF statement, but instead of returning it, it returns a result with yield once, suspending and continuing their state between each result, to automatically implement the iterative protocol. In other words, yield is a syntactic sugar, and the internal implementation supports the iterator protocol, while the yield is a state machine that maintains the status of suspend and continue.

def zrange (n):
i = 0
While I < n:
Yield I
i+= 1
Zrange = Zrange (3)
Print Zrange
print [i-I in Zrange]

In fact, the generator function returns an iterator to the generator. The term "generator iterator" is often referred to as the "generator". It is important to note that the generator is a special kind of iterator. As an iterator, the generator must define some methods, one of which is next (). As with iterators, we can use the next () function to get the next value.

The following describes how the generator works:

def zrange (n):
print ' beginning of Zrange '
i = 0
While I < n:
print ' Before yield ', I
Yield I
i + = 1
print ' After yield ', I
print ' Endding of Zrange '
Zrange = Zrange (3)
print '-------------------------'
Print Zrange.next ()
print '------------------'
Print Zrange.next ()
print '------------------'
Print Zrange.next ()
print '------------------'
Print Zrange.next ()
print '------------------'

From the results you can see:

    • When the generator function is called, the function simply returns a generator object and does not execute.
    • When the next () method is called for the first time, the generator function begins execution, and execution stops at the yield statement
      • The return value of the next () method is the argument at the yield statement (yielded value)
    • When the next () method continues to be called, the function continues at the last stop yield statement and stops at the next yield and throws a stopiteration exception if no yield is followed

Generator's send () and close () methods

There are two other important methods in the generator: Send () and close ().

    • Send (value):

From the previous understanding, the next () method can restore the generator State and continue execution, in fact, send () is a method other than next () recovery generator.

In Python 2.5, the yield statement becomes the yield expression, which means that yield can have a value, which is the parameter of the Send () method, so Send (None) and next () are equivalent. Similarly, the return values of next () and send () are the arguments at the yield statement (yielded value)

Note about the Send () method: The generator must be in a pending state before calling send to pass in a value other than none, otherwise an exception will be thrown. That is, the first call is to use the next () statement or send (None), because there is no yield statement to receive this value.

    • Close ():

This method is used to close the generator, and calling next or send again after the shutdown generator throws a Stopiteration exception.

Python iterators and generators

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.