diff --git a/examples/plural6.py b/examples/plural6.py index 004f57e..d7e824e 100755 --- a/examples/plural6.py +++ b/examples/plural6.py @@ -20,9 +20,9 @@ class LazyRules: def __init__(self): self.pattern_file = open(self.rules_filename, encoding='utf-8') self.cache = [] - self.cache_index = 0 def __iter__(self): + self.cache_index = 0 return self def __next__(self): diff --git a/iterators.html b/iterators.html index 0672236..a026faa 100755 --- a/iterators.html +++ b/iterators.html @@ -220,9 +220,9 @@ All three of these class methods, __init__, __iter__, def __init__(self): self.pattern_file = open(self.rules_filename, encoding='utf-8') self.cache = [] - self.cache_index = 0 def __iter__(self): + self.cache_index = 0 return self def __next__(self): @@ -255,8 +255,7 @@ rules = LazyRules() def __init__(self): self.pattern_file = open(self.rules_filename, encoding='utf-8') - self.cache = [] - self.cache_index = 0 + self.cache = []
  1. When we instantiate the LazyRules class, open the pattern file but don’t read anything from it. (That comes later.)
  2. After opening the patterns file, initialize the cache and the cache index position. You’ll use these later (in the __next__() method) as you read lines from the pattern file. @@ -295,11 +294,12 @@ rules = LazyRules()

    And now back to our show.

        def __iter__(self):       
    +        self.cache_index = 0
             return self           
     
    1. The __iter__() method will be called every time someone — say, a for loop — calls iter(rules). -
    2. The only thing the __iter__() method needs to do is return an iterator. In this case, it returns self, which signals that this class defines a __next__() method which will take care of returning values throughout the iteration. +
    3. The one thing that every __iter__() method must do is return an iterator. In this case, it returns self, which signals that this class defines a __next__() method which will take care of returning values throughout the iteration.
        def __next__(self):