擅长:python、mysql、java
<p>Python中的<code>is</code>运算符检查这两个参数是否引用内存中的同一对象;它与C中的<code>is</code>运算符不同。</p>
<p><a href="http://docs.python.org/reference/expressions.html#notin" rel="noreferrer">From the docs</a>:</p>
<blockquote>
<p>The operators is and is not test for object identity: x is y is true if and only if x and y are the same object. x is not y yields the inverse truth value. </p>
</blockquote>
<p>在这种情况下,您需要的是<a href="http://docs.python.org/release/2.6/library/functions.html?highlight=isinstance#isinstance" rel="noreferrer">^{<cd3>}</a>。</p>
<blockquote>
<p>Return true if the object argument is an instance of the classinfo argument, or of a (direct or indirect) subclass thereof. </p>
</blockquote>
<pre><code>>>> class animal(object): pass
>>> class dog(animal): pass
>>> myDog = dog()
>>> isinstance(myDog, dog)
True
>>> isinstance(myDog, animal)
True
</code></pre>
<p>然而,惯用的Python要求您(几乎)永远不要进行类型检查,而是依赖<a href="http://en.wikipedia.org/wiki/Duck_typing" rel="noreferrer">duck-typing</a>进行多态行为。使用<code>isinstance</code>来理解继承并没有什么错,但是通常应该在“生产”代码中避免它。</p>