Skip to content

Commit de8c842

Browse files
committed
Duck iterator
1 parent c2b3a1a commit de8c842

File tree

2 files changed

+32
-0
lines changed

2 files changed

+32
-0
lines changed

README.md

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1046,6 +1046,24 @@ class MyCollection:
10461046
yield el
10471047
```
10481048

1049+
### Iterator
1050+
```python
1051+
class Counter:
1052+
def __init__(self):
1053+
self.i = 0
1054+
def __next__(self):
1055+
self.i += 1
1056+
return self.i
1057+
def __iter__(self):
1058+
return self
1059+
```
1060+
1061+
```python
1062+
>>> counter = Counter()
1063+
>>> next(counter), next(counter), next(counter)
1064+
(1, 2, 3)
1065+
```
1066+
10491067
### Callable
10501068
```python
10511069
class Counter:

index.html

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -981,6 +981,20 @@ <h3 id="collection">Collection</h3>
981981
<span class="hljs-keyword">for</span> el <span class="hljs-keyword">in</span> self.a:
982982
<span class="hljs-keyword">yield</span> el
983983
</code></pre>
984+
<h3 id="iterator-1">Iterator</h3>
985+
<pre><code class="python language-python hljs"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Counter</span>:</span>
986+
<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">__init__</span><span class="hljs-params">(self)</span>:</span>
987+
self.i = <span class="hljs-number">0</span>
988+
<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">__next__</span><span class="hljs-params">(self)</span>:</span>
989+
self.i += <span class="hljs-number">1</span>
990+
<span class="hljs-keyword">return</span> self.i
991+
<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">__iter__</span><span class="hljs-params">(self)</span>:</span>
992+
<span class="hljs-keyword">return</span> self
993+
</code></pre>
994+
<pre><code class="python language-python hljs"><span class="hljs-meta">&gt;&gt;&gt; </span>counter = Counter()
995+
<span class="hljs-meta">&gt;&gt;&gt; </span>next(counter), next(counter), next(counter)
996+
(<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>)
997+
</code></pre>
984998
<h3 id="callable">Callable</h3>
985999
<pre><code class="python language-python hljs"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Counter</span>:</span>
9861000
<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">__init__</span><span class="hljs-params">(self)</span>:</span>

0 commit comments

Comments
 (0)