From de8c842468112bda60f19d225fecba0e23b710d7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= <sornjure@gmail.com> Date: Thu, 27 Jun 2019 19:43:28 +0200 Subject: [PATCH] Duck iterator --- README.md | 18 ++++++++++++++++++ index.html | 14 ++++++++++++++ 2 files changed, 32 insertions(+) diff --git a/README.md b/README.md index 1bd66b9..e1cd5d6 100644 --- a/README.md +++ b/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: diff --git a/index.html b/index.html index fea4acc..bc6664b 100644 --- a/index.html +++ b/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">>>> </span>counter = Counter() +<span class="hljs-meta">>>> </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>