擅长:python、mysql、java
<p>你需要小心继承:</p>
<pre><code>>>> class Foo:
def __eq__(self, other):
if isinstance(other, self.__class__):
return self.__dict__ == other.__dict__
else:
return False
>>> class Bar(Foo):pass
>>> b = Bar()
>>> f = Foo()
>>> f == b
True
>>> b == f
False
</code></pre>
<p>更严格地检查类型,例如:</p>
<pre><code>def __eq__(self, other):
if type(other) is type(self):
return self.__dict__ == other.__dict__
return False
</code></pre>
<p>除此之外,你的方法也会很好,这就是特殊方法的作用。</p>