"Python" "Control Flow" "Iterate objects, iterators, generators"

Source: Internet
Author: User

#14.1 sentence Class first edition, Word sequence
#栗子14-1 bar sentence divided into Word sequence
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 __getitem__ (self, item):
return Self.words[item]
def __len__ (self): #为了完善序列, we implement the __len__ method, in order for the object to iterate, there is no need to implement this method
Return Len (self.words)
def __repr__ (self):
Return ' sentence (%s) '% Reprlib.repr (self.text) #生成大型数据结构的简略字符串表示
#栗子14-2 Test whether sentence can be iterated
s = Sentence (' "The Tiem has Come,", the Walrus said, ')
Print (s) #Sentence (' "The Tiem ha ... Walrus said, ')
For word in S:
Print (word)
‘‘‘
The
Tiem
Has
Come
The
Walrus
Said
‘‘‘
Print (list (s)) #[' The ', ' tiem ', ' has ', ' Come ', ' the ', ' walrus ', ' said ']
# reason why the "parse" sequence can be iterated
‘‘‘
(1) Check whether the built-in object implements the __iter__ method, call him if it is implemented, get an iterator
(2) 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)
(3) If the attempt fails, Python runs out of the typeerror exception, usually prompting "C object is not itrable"
‘‘‘

#14.2 Iterative object and iterator comparison
# iterable and Iterator abstract base classes. The former is the parent of the latter, the latter is based on the former __iter__, and the new __next__ method is added.
There's a way in #Iterator.
Import ABC
@classmethod
def __subclasshook__ (cls,c):
If CLS is ABC. Iterator:
if ("__next__" in b.__dict__ for B in c.__mro__) and
Any ("__iter__" in b.__dict__ for B in c.__mro__)):
Return True
Return notimplemented
#考虑到Lib the recommendations in/types.py, and the logical implementation in lib/_collections_abc.py, the best way to check whether an object x is an iterator is to call Isinstance (X,ABC. Iterator). Thanks to the iterator.__subclasshook__ method, even if the object X
#... The class that belongs to is not a real subclass of the iterator class or a virtual subclass, so check
Classes in #使用栗子14-1, building iterators with the ITER () function, using Iterators with the next () function
S3 = Sentence (' Pig and Pepper ')
it = ITER (S3)
Print (IT) #<iterator object at 0x0000000002948a58>
Print (Next (IT)) #Pig
Print (Next (IT)) #and
Print (Next (IT)) #Pepper
#print (Next (IT)) #StopIteration
After print (list (it)) #[] The end of the head, the iterator is useless
Print (ITER (S3)) #[' Pig ', ' and ', ' Pepper '] to iterate again, to rebuild the iterator


The #因为内置的 iter (...) function will do special processing of the sequence, so the 1th version of the sentence class can iterate. The next step is to implement the standard iterative protocol

















"Python" "Control Flow" "Iterate objects, iterators, 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.