Behind the object can be iterative

Iterative loop may be two kinds of objects

# A method 
S = ' ABC ' # iterables 
for I in S:
     Print (I)
 
# Method Two    
IT = ITER (S) # Construction iterators
 the while True:
     the try :
         Print (Next (ITER (IT)))
     the except the StopIteration:
         del S
         BREAK 

iterator comprising: __ next __, __ iter__ Method
  1. No parameters __next_ _ the method returns to the next element in the sequence, no element raise StopIteration
  2 .__ iter__ method for the iterator can iteration
iterables: __ iter__ method

__getitem__ method

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 __len__(self):
        return len(self.words)

    def __repr__(self):
        return 'Sentence(%s)' % reprlib.repr(self.text)

    def __getitem__(self, index):
        return self.words[index]

s3=Sentence('pig and pepper')

for i in s3:
    print(i)

'''
The reason is because s3 can be iterative: __ getitem__ method
The reason python in the sequence can be iterative: have achieved __getitem__ method.
Step 1.python checked whether the object is an iterative method to check whether the implemented __iter__
2. If there is no __iter__, but realized __getitem__ method, python interpreter creates an iterator, try to get the elements by index
3. If the attempt fails will throw an error Typeerror
'''

 

Guess you like

Origin www.cnblogs.com/liuer-mihou/p/11903519.html