Browse Source

context managers and some decorators

master
Julio Biason 8 years ago
parent
commit
9e55991035
  1. 92
      python.html

92
python.html

@ -1096,6 +1096,47 @@ Julio
>>> # retrieve
</code></pre>
</section>
<section>
<h5>Decorators mais comuns:</h5>
<ul>
<li><code>@property</code></li>
<li><code>@staticmethod</code></li>
</ul>
</section>
<section>
<h5><code>@property</code></h5>
<pre><code class='hljs'>
&gt;&gt;&gt; class CheckConn(object):
&gt;&gt;&gt; def __init__(self, func):
&gt;&gt;&gt; self._func = func
&gt;&gt;&gt;
&gt;&gt;&gt; @property
&gt;&gt;&gt; def func(self):
&gt;&gt;&gt; return self._func
&gt;&gt;&gt;
&gt;&gt;&gt; @func.setter
&gt;&gt;&gt; def func(self, value):
&gt;&gt;&gt; self._func = func
</code></pre>
</section>
<section>
<h5><code>@staticmethod</code></h5>
<pre><code class='hljs'>
&gt;&gt;&gt; class CheckConn(object):
&gt;&gt;&gt; def __init__(self, func):
&gt;&gt;&gt; self._func = func
&gt;&gt;&gt;
&gt;&gt;&gt; @staticmethod
&gt;&gt;&gt; def from_text(self, text):
&gt;&gt;&gt; return CheckConn(getattr(self, text))
</code></pre>
</section>
</section>
<section>
@ -1196,6 +1237,57 @@ Julio
</section>
<section>
<section>
<h3>Context Managers</h3>
<p>
<i>Context Managers</i> são usados como "marcadores"
para entrada e saída de pontos específicos.
</p>
</section>
<section>
<h3>Context Managers</h3>
<pre><code class="hljs">
&gt;&gt;&gt; class Connection(object):
&gt;&gt;&gt; def __init__(self):
&gt;&gt;&gt; self._conn = None
&gt;&gt;&gt;
&gt;&gt;&gt; def __enter__(self):
&gt;&gt;&gt; self._conn = self._make_connection()
&gt;&gt;&gt; return self._conn
&gt;&gt;&gt;
&gt;&gt;&gt; def __exit__(self, exc_type, exc_value, traceback):
&gt;&gt;&gt; self._conn.close()
&gt;&gt;&gt; if exc_type: # then exc_value and traceback
&gt;&gt;&gt; print "Exception!", exc_type, exc_value
&gt;&gt;&gt; print traceback
</code></pre>
<pre><code class="hljs">
&gt;&gt;&gt; with Connection() as connection:
&gt;&gt;&gt; connection.request('Value')
</code></pre>
</section>
<section>
<h3>Context Managers vs Exceptions</h3>
<pre><code class="hljs">
&gt;&gt;&gt; try:
&gt;&gt;&gt; conn = self._make_connection()
&gt;&gt;&gt; conn.request('value')
&gt;&gt;&gt; finally:
&gt;&gt;&gt; conn.close()
&gt;&gt;&gt; except Exception as exc: # Bare exceptions are BAAAADDD!
&gt;&gt;&gt; print 'Exception!', exc
</code></pre>
</section>
</section>
<section>
<section>
<h3>Docstrings</h3>

Loading…
Cancel
Save