Python can iterate over objects, iterators, generator differences __python

Source: Internet
Author: User
Tags generator
This article briefly discusses the relationship between an iterative object, an iterator, and a generator.



brief relationship diagram of three





Iterative objects and iterators


At first I thought the two were equivalent, but it turned out to be the case; The following directly throws a conclusion: 1 The Iteration object contains an iterator.
2 If an object has a __iter__ method, it is an iterative object, and if an object has a next method, it is an iterator.
3 Define an iterative object, you must implement the __iter__ method; define iterators, you must implement __iter__ and next methods.


You may ask whether conclusion 3 is a bit contradictory to conclusion 2. Since an object has a next method is an iterator, why should the iterator implement both methods simultaneously? Because of conclusion 1, the iterator is also an iterative object, so the iterator must also implement the __iter__ method.

Describe the two approaches involved:

1) __iter__ ()

This method returns an instance of the iterator class for the current object . Because iterative objects and iterators implement this method, there are two ways to do so.

To use as an iterative object class, to return an instance of the iterator class for the iteration object.

Writing two: For the iterator class to be written, return directly to self (that is, itself), representing itself as its own iterator.

Maybe a little dizzy, it does not matter, the following will give two examples of the wording, we combine specific examples to see.


2) Next ()

Returns each step of the iteration, and when implemented, note that the stopiteration exception is thrown when the boundary is last exceeded.


Here's an example of an iterative object and an iterator:

#!/usr/bin/env python
# Coding=utf-8


class MyList (object):            # defines an Iterative object class

    def __init__ (self, num):
        Self.data = num          # top Border

    def __iter__ (self):
        return Mylistiterator (self.data)  # Returns an instance


of the iterator class for the Iteration object Class Mylistiterator (object):    # Defines the iterator class, which is the iterator class

    def __init__ (self, data) of the MyList iteration object:
        self.data = Data         # upper boundary
        self.now = 0             # Current iteration value, initially 0

    def __iter__ (self):              return Self # Returns an instance of the iterator class for the object Because you are an iterator, return self

    def next (self):              # The method that the iterator class must implement while
        Self.now < self.data:
            Self.now = 1
            return self.now-1  # returns the current iteration value
        raise Stopiteration      # exceeds the upper bounds, throws an exception


my_list = MyList (5)              # Get an Iterated object
print type (my_list) # to              return the object's type

My_list_iter = iter (my_list)     # to get an iterator instance of the object, The ITER function will explain in detail the
print type (my_list_iter) for


i in my_list:                # iteration
    Print I

Run Result:



Question: The ITER function appears in the above example, what is this thing. Is it related to the __iter__ method?
In fact, the function is closely related to iterations, and by printing "help Iter" in the Python command line, you know that it has the following two uses.

Usage One: ITER (callable, Sentinel)
Call callable until its return value equals Sentinel. The callable can be a function, a method, or an instance that implements the __call__ method.

Usage Two: ITER (collection)
1 is used to return the iterator instance of the collection object, where the collection I think represents an iterative object, that is, the object must implement the __iter__ method; In fact, the ITER function is very closely related to the __iter__ method, ITER () is the __iter__ () that invokes the object directly, and the return result of __iter__ () as its return value, so this usage is often referred to as "creating an iterator."
2 The ITER function can display the call, or when executing "for I in obj:", the Python interpreter automatically invokes ITER (obj) at the first iteration, and the subsequent iteration invokes the iterator's next method. The For statement automatically handles the last Stopiteration exception thrown.


With the above example, it is believed that there is a more specific understanding of the iterative objects and iterators, so what does the generator have to do with them? Here's a quick talk.



Build Device


The generator is a special iterator that automatically implements the iterator protocol (the __iter__ and Next methods)without the need to manually implement the two methods.

The generator can change the current iteration value during the iteration, while modifying the current iteration value of the ordinary iterator often occurs abnormally , affecting the execution of the program.


Look at an example of a builder:

#!/usr/bin/env python
# coding=utf-8


def myList (num):      # define generator
    now = 0           # Current iteration value, initially 0 while
    < num:
        val = (yield now)                      returns the current iteration value and accepts the possible send value; yield explains now
        = Today + 1 if Val is None else Val  va L is None, the iteration value is 1, otherwise the current iteration value is val

my_list = myList (5)   # Gets a generator object

print My_list.next ()  # Returns the current iteration value
print My_list.next ()

my_list.send (3)       # To reset the current iteration value
print my_list.next ()

print dir (my_list    # Returns the name of the method owned by the object, and you can see __ITER__ and next in the

Run Result:



functions with yield keywords are generators , yield can be interpreted as return, and the following values are returned to the caller. The difference is that when return returns, the function is released and the generator does not. When you call the next method directly or use the For statement for the next iteration, the generator executes from the next sentence of yield until the next yield is encountered.



Resources:

Python Core Programming Second Edition 11.10, 13.13.3 section

Fully understand Python iterative objects, iterators, generators

Drill down on iterators and generators in Python

How to better understand Python iterators and generators


If there is any inappropriate place, also hope to contain and point out, thank


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.