擅长:python、mysql、java
<p>根据<a href="http://docs.python.org/library/sets.html" rel="nofollow">the documentation</a>,您需要定义<code>__hash__()</code>和{<cd2>},以便自定义类正确使用<code>set</code>或{<cd4>},因为这两个都是使用CPython中的哈希表实现的。在</p>
<p>如果实现<code>__hash__</code>,请记住如果<code>a == b</code>,那么{<cd7>}必须等于<code>hash(b)</code>。我建议为您的简单类提供以下更直接的实现,而不是比较整个<code>__dict__</code>s:</p>
<pre><code>class Foo(object):
def __init__(self, myid):
self.myid = myid
def __eq__(self, other):
return isinstance(other, self.__class__) and other.myid == self.myid
def __hash__(self):
return hash(self.myid)
</code></pre>
<p>如果对象包含可变属性,则不应将其放在集合中或将其用作字典键。在</p>