diff --git a/iterators.html b/iterators.html index 4974cde..0672236 100755 --- a/iterators.html +++ b/iterators.html @@ -219,10 +219,10 @@ All three of these class methods, __init__, __iter__, def __init__(self): self.pattern_file = open(self.rules_filename, encoding='utf-8') - - def __iter__(self): self.cache = [] self.cache_index = 0 + + def __iter__(self): return self def __next__(self): @@ -255,14 +255,11 @@ rules = LazyRules() def __init__(self): self.pattern_file = open(self.rules_filename, encoding='utf-8') - - def __iter__(self): - self.cache = [] + self.cache = [] self.cache_index = 0
  1. When we instantiate the LazyRules class, open the pattern file but don’t read anything from it. (That comes later.) -
  2. The __iter__() method is going to be called after you instantiate the class, assign it to rules, and call iter(rules) to create the iterator. It would also get called again if you created a new iterator from the same rules object. -
  3. That means that this is a right place to initialize the cache and the cache index position. You’ll use these later (in the __next__() method) as you read the patterns from the pattern file. +
  4. 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.

Before we continue, let’s take a closer look at rules_filename. It’s not defined within the __iter__() method. In fact, it’s not defined within any method. It’s defined at the class level. It’s a class variable, and although you can access it just like an instance variable (self.rules_filename), it is shared across all instances of the LazyRules class. @@ -298,13 +295,11 @@ rules = LazyRules()

And now back to our show.

    def __iter__(self):       
-        self.cache_index = 0  
-        return self           
+        return self           
 
  1. The __iter__() method will be called every time someone — say, a for loop — calls iter(rules). -
  2. This is the place to reset the counter that we’re going to use to retrieve items from the cache (that we haven’t built yet — patience, grasshopper). -
  3. Finally, the __iter__() method returns self, which signals that this class will take care of returning its own values throughout an iteration. +
  4. 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.
    def __next__(self):