擅长:python、mysql、java
<h2>鸭子打字</h2>
<pre><code>try:
iterator = iter(theElement)
except TypeError:
# not iterable
else:
# iterable
# for obj in iterator:
# pass
</code></pre>
<h2>类型检查</h2>
<p>使用<a href="https://docs.python.org/library/abc.html" rel="noreferrer">Abstract Base Classes</a>。它们至少需要Python2.6,并且只适用于新样式的类。</p>
<pre><code>from collections.abc import Iterable # import directly from collections for Python < 3.3
if isinstance(theElement, Iterable):
# iterable
else:
# not iterable
</code></pre>
<p>但是,<code>iter()</code>更可靠,如<a href="https://docs.python.org/library/collections.abc.html#collections.abc.Iterable" rel="noreferrer">by the documentation</a>所述:</p>
<blockquote>
<p>Checking <code>isinstance(obj, Iterable)</code> detects classes that are
registered as Iterable or that have an <code>__iter__()</code> method, but
it does not detect classes that iterate with the <code>__getitem__()</code>
method. The only reliable way to determine whether an object
is iterable is to call <code>iter(obj)</code>.</p>
</blockquote>