Python advanced Programming-part1 generators and iterators

Source: Internet
Author: User
Tags generator

Iterators and generators are a topic that Python scholars often talk about and I can't mundane because it's worth summing up.


Iterators

An iterator is a tool that operates on an iterative object and spits out one element at a time through the next method. We used the for. In.. The internal use of iterators is the function of an iterator.

If you want to customize an iterator class, you need to meet the following criteria:

    • The __iter__ method needs to be defined in the class to return self itself, indicating that this is an iterator;

    • The next method needs to be defined to return the value of the iteration, which should contain the judgment of the stopiteration exception

Try to write an example of a custom iterator class (modeled after the Python Advanced Programming book):

Class customiter (object):     def __init__ (self, step):         self.step = step                 def __iter__ (self):         return self        def next (self):         if self.step == 0:             return StopIteration                 self.step -=1         Return self.step    i = customiter (2)    #此处如果换为for  i in  customiter (2), no subsequent next manual calls are required,                     #也不会出现StopIteration的异常 because the for loop internally implements the next call Print i.next () Print i.next () Print i.next () The result of the operation is as follows:10<type  ' exceptions. Stopiteration ' >

Iterators are actually an underlying feature and concept, but provide a support for the generator.


Generator

There is a memory function to pause and resume the performance of execution, using yield instead of the return statement, indicating that a value is returned each time and execution is paused. When called again by external next, the function context is automatically resumed from the paused position until the yield statement is encountered again.

Let's understand from the code that it's not quite clear:

#!/usr/bin/env python#encoding:utf-8def TestGenerator (): For X in ("First", "second", "third"): print "The IS "+ x Yield x #每次返回x之后, will stop print" Do other things "B = TestGenerator () print b.next () print U" \ n------Execute next again ():------\ n "#再次运行nextprint b.next () The result is as follows: This is firstfirst------execute next again:------Do and Thingsthis is Secondsecond

Other forms of the generator:

The yield expression , which is the existence of var = (yield) in the function body, means that the data sent in by the client to call send (the method of the Generator object) can be obtained

Let's talk about it later, headache.

This article is from the "Nameless" blog, please be sure to keep this source http://xdzw608.blog.51cto.com/4812210/1601317

Python advanced Programming-part1 generators and iterators

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.