[Python] iterator

Iteration is a way to access the collection elements. Iterator can remember the object is a traverse position. Iterator object began a visit from the first element of the collection until all the elements are accessed session is over. Iterator can only move forward not backward.

1. iterables

We already know that you can use to list, tuple, str and other types of data for ... in loop syntax ... from which data to use in order to get, we have such a process is called traversal, also called iteration.

How can you tell whether an object can iterate

Can use the isinstance () determines whether an object is an object Iterable:

In [50]: from collections import Iterable

In [51]: isinstance([], Iterable)
Out[51]: True

In [52]: isinstance({}, Iterable)
Out[52]: True

In [53]: isinstance('abc', Iterable)
Out[53]: True

In [54]: isinstance(mylist, Iterable)
Out[54]: False

In [55]: isinstance(100, Iterable)
Out[55]: False

3. The nature of iterables

Our analysis of the object can be an iterative process of iteration and found that for each iteration (ie for ... in ... in every cycle) will return the next data object has been read back data until the iterator All data after the end. Well, in this process, there should be a "person" to record each visit to the first few data for each iteration to return the next data. We put this data to help us perform iterations of "people" called iterator (Iterator).

Iterables essence is that we can provide to us in the middle of such a "man" that help us traverse iterator use its iteration.

Iterables __iter__ method provided by an iterator to us, when we iteration of an iterative object, in fact, is to first get the object provides an iterator, and get turn by each of the objects of this iterator a data.

So in other words, a method with a target __iter__, is an iteration object.

# isinstance([11,22,33], Iterable)                                                                               
# Out[8]: True

class MyList(object):

    def __init__(self):
        self.container = []

    def add(self, item):
        self.container.append(item)

    def __iter__(self):
        pass

mylist = MyList()

from collections.abc import Iterable

print(isinstance(mylist, MyList))

# 这回测试发现添加了__iter__方法的mylist对象已经是一个可迭代对象了

Guess you like

Origin www.cnblogs.com/liudianer/p/11805820.html