Browse Source

Duck iterator

pull/36/head
Jure Šorn 5 years ago
parent
commit
de8c842468
2 changed files with 32 additions and 0 deletions
  1. 18
      README.md
  2. 14
      index.html

18
README.md

@ -1046,6 +1046,24 @@ class MyCollection:
yield el
```
### Iterator
```python
class Counter:
def __init__(self):
self.i = 0
def __next__(self):
self.i += 1
return self.i
def __iter__(self):
return self
```
```python
>>> counter = Counter()
>>> next(counter), next(counter), next(counter)
(1, 2, 3)
```
### Callable
```python
class Counter:

14
index.html

@ -981,6 +981,20 @@ creature = Creature(Point(<span class="hljs-number">0</span>, <span class="hljs
<span class="hljs-keyword">for</span> el <span class="hljs-keyword">in</span> self.a:
<span class="hljs-keyword">yield</span> el
</code></pre>
<h3 id="iterator-1">Iterator</h3>
<pre><code class="python language-python hljs"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Counter</span>:</span>
<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">__init__</span><span class="hljs-params">(self)</span>:</span>
self.i = <span class="hljs-number">0</span>
<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">__next__</span><span class="hljs-params">(self)</span>:</span>
self.i += <span class="hljs-number">1</span>
<span class="hljs-keyword">return</span> self.i
<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">__iter__</span><span class="hljs-params">(self)</span>:</span>
<span class="hljs-keyword">return</span> self
</code></pre>
<pre><code class="python language-python hljs"><span class="hljs-meta">&gt;&gt;&gt; </span>counter = Counter()
<span class="hljs-meta">&gt;&gt;&gt; </span>next(counter), next(counter), next(counter)
(<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>)
</code></pre>
<h3 id="callable">Callable</h3>
<pre><code class="python language-python hljs"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Counter</span>:</span>
<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">__init__</span><span class="hljs-params">(self)</span>:</span>

|||||||
100:0
Loading…
Cancel
Save