mirror of
https://github.com/kennethreitz/dive-into-python3.git
synced 2026-06-05 23:10:17 +00:00
sigh
This commit is contained in:
+1
-1
@@ -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
@@ -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>①</span></a>
|
||||
<a> self.cache = [] <span class=u>②</span></a>
|
||||
self.cache_index = 0</code></pre>
|
||||
<a> self.cache = [] <span class=u>②</span></a></code></pre>
|
||||
<ol>
|
||||
<li>When we instantiate the <code>LazyRules</code> class, open the pattern file but don’t read anything from it. (That comes later.)
|
||||
<li>After opening the patterns file, initialize the cache and the cache index position. You’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>①</span></a>
|
||||
self.cache_index = 0
|
||||
<a> return self <span class=u>②</span></a>
|
||||
</code></pre>
|
||||
<ol>
|
||||
<li>The <code>__iter__()</code> method will be called every time someone — say, a <code>for</code> loop — 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>①</span></a>
|
||||
|
||||
Reference in New Issue
Block a user