擅长:python、mysql、java
<p>Python有一个类似的函数:<a href="http://docs.python.org/reference/datamodel.html#object.__cmp__" rel="nofollow">^{<cd1>}</a>。</p>
<p>我现在知道你在问Python3。<a href="http://docs.python.org/release/3.0.1/whatsnew/3.0.html" rel="nofollow">Their "whats new" suggests</a>:</p>
<pre>
The cmp() function should be treated as gone, and the __cmp__() special method
is no longer supported. Use __lt__() for sorting, __eq__() with __hash__(), and
other rich comparisons as needed. (If you really need the cmp() functionality,
you could use the expression (a > b) - (a < b) as the equivalent for cmp(a, b).)
</pre>
<p>所以看起来你可以做些</p>
<pre><code>def compareTo(self, that):
return ((self > that) - (self < that))
</code></pre>
<p>或者</p>
<pre><code>@classmethod
def compare(cls, a, b):
return ((a > b) - (a < b))
</code></pre>
<p>在实现<code>__gt__()</code>和<code>__lt__()</code>之后。</p>
<p>然后您可以使用:</p>
<pre><code>f1 = Foo(1,1)
f2 = Foo(2,2)
f1.compareTo(f2)
Foo.compare(f1,f2)
</code></pre>
<p>这将为您提供同等的功能。</p>