objects, iterators, and generators that can be iterated
Iteration is the cornerstone of data processing. Scan memory for data sets that don't fit in, we're looking for an inert way to get data items, which is to get one data item at a time. This is the iterator pattern.
1 Iterative objects
1.1 Why the sequence can be iterated
When the interpreter needs to iterate over object x, it automatically calls ITER (x), and the built-in ITER function has the following effects:
Check to see if the object implements the Iter method and invoke it if it is implemented to get an iterator.
If the Iter method is not implemented, but the GetItem method is implemented, Python creates an iterator that attempts to get the element in order (starting at index 0)
If the attempt fails, Python throws a TypeError exception, usually prompting "C object is not Iterable", where c is the target iteration object
2 iterators
Interface for 2.1 iterators
The standard iterator interface has two methods:
Next: Returns the next available element, if there is no element, throws Stopiteration
iter: Returns self to use iterators where an iterator should be used, for example in a for loop
6.2.21 Classic Iterators
#可迭代对象和迭代器一定不能在一个对象中同时实现, for a typical iterator.
Import re
Import Reprlib
?
Re_word = Re.compile (' \w+ ')
?
Class sentence:
def __init__(self,text): self.text = text self.words = RE_WORD.findall(text)def __iter__(self): return SentenceIterator(self.words)def __repr__(self): return ‘Sentence(%s)‘ % reprlib.repr(self.text)
#实现迭代器
Class Sentenceiterator (Self,words):
def Init(self,words):
Self.words = words
Self.index = 0
def next(self):
Try
Word = Self.words[self.index]
Except Indexerror:
Raise Stopiteration ()
Self.index + = 1
return word
def iter(self):
Bo Zhong Entertainment platform development and Python learning