Browse Source

Duck types

pull/46/head
Jure Šorn 4 years ago
parent
commit
3cf7f44318
2 changed files with 6 additions and 2 deletions
  1. 4
      README.md
  2. 4
      index.html

4
README.md

@ -1174,6 +1174,8 @@ class Counter:
### Context Manager
* **Enter() should lock the resources and return an object.**
* **Exit() should release the resources.**
* **Any exception that happens inside the with block is passed to the exit() method.**
* **If it wishes to suppress the exception it must return a true value.**
```python
class MyOpen():
def __init__(self, filename):
@ -1181,7 +1183,7 @@ class MyOpen():
def __enter__(self):
self.file = open(self.filename)
return self.file
def __exit__(self, *args):
def __exit__(self, exc_type, exc_value, traceback):
self.file.close()
```

4
index.html

@ -1116,13 +1116,15 @@ Z = dataclasses.make_dataclass(<span class="hljs-string">'Z'</span>, [<span clas
<div><h3 id="contextmanager">Context Manager</h3><ul>
<li><strong>Enter() should lock the resources and return an object.</strong></li>
<li><strong>Exit() should release the resources.</strong></li>
<li><strong>Any exception that happens inside the with block is passed to the exit() method.</strong></li>
<li><strong>If it wishes to suppress the exception it must return a true value.</strong> </li>
</ul><pre><code class="python language-python hljs"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">MyOpen</span><span class="hljs-params">()</span>:</span>
<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">__init__</span><span class="hljs-params">(self, filename)</span>:</span>
self.filename = filename
<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">__enter__</span><span class="hljs-params">(self)</span>:</span>
self.file = open(self.filename)
<span class="hljs-keyword">return</span> self.file
<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">__exit__</span><span class="hljs-params">(self, *args)</span>:</span>
<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">__exit__</span><span class="hljs-params">(self, exc_type, exc_value, traceback)</span>:</span>
self.file.close()
</code></pre></div>

Loading…
Cancel
Save