This commit is contained in:
Mark Pilgrim
2009-08-17 22:05:10 -04:00
parent 8c4fd325a9
commit cf721a18c4
2 changed files with 5 additions and 5 deletions
+1 -1
View File
@@ -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):
+4 -4
View File
@@ -220,9 +220,9 @@ All three of these class methods, <code>__init__</code>, <code>__iter__</code>,
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()</code></pre>
def __init__(self):
<a> self.pattern_file = open(self.rules_filename, encoding='utf-8') <span class=u>&#x2460;</span></a>
<a> self.cache = [] <span class=u>&#x2461;</span></a>
self.cache_index = 0</code></pre>
<a> self.cache = [] <span class=u>&#x2461;</span></a></code></pre>
<ol>
<li>When we instantiate the <code>LazyRules</code> class, open the pattern file but don&#8217;t read anything from it. (That comes later.)
<li>After opening the patterns file, initialize the cache and the cache index position. You&#8217;ll use these later (in the <code>__next__()</code> method) as you read lines from the pattern file.
@@ -295,11 +294,12 @@ rules = LazyRules()</code></pre>
<p>And now back to our show.
<pre class=pp><code><a> def __iter__(self): <span class=u>&#x2460;</span></a>
self.cache_index = 0
<a> return self <span class=u>&#x2461;</span></a>
</code></pre>
<ol>
<li>The <code>__iter__()</code> method will be called every time someone&nbsp;&mdash;&nbsp;say, a <code>for</code> loop&nbsp;&mdash;&nbsp;calls <code>iter(rules)</code>.
<li>The only thing the <code>__iter__()</code> method needs to do is return an iterator. In this case, it returns <var>self</var>, which signals that this class defines a <code>__next__()</code> method which will take care of returning values throughout the iteration.
<li>The one thing that every <code>__iter__()</code> method must do is return an iterator. In this case, it returns <var>self</var>, which signals that this class defines a <code>__next__()</code> method which will take care of returning values throughout the iteration.
</ol>
<pre class=pp><code><a> def __next__(self): <span class=u>&#x2460;</span></a>