<p>您可以实现特殊方法<code>__lt__</code>、<code>__gt__</code>等来实现自定义类型的默认运算符。有关它们的详细信息,请参见<a href="http://docs.python.org/py3k/reference/datamodel.html#object.__lt__">language reference</a>。</p>
<p>例如:</p>
<pre><code>class Foo:
def __init__ (self, a, b):
self.a = a
self.b = b
def __lt__ (self, other):
if self.a == other.a:
return self.b < other.b
return self.a < other.b
def __gt__ (self, other):
return other.__lt__(self)
def __eq__ (self, other):
return self.a == other.b and self.b == other.b
def __ne__ (self, other):
return not self.__eq__(other)
</code></pre>
<p>或者正如straac在评论中所说,您可以使用<a href="http://docs.python.org/py3k/library/functools.html#functools.total_ordering">^{<cd3>}</a>装饰器保存一些类型:</p>
<pre><code>@functools.total_ordering
class Foo:
def __init__ (self, a, b):
self.a = a
self.b = b
def __lt__ (self, other):
if self.a == other.a:
return self.b < other.b
return self.a < other.b
def __eq__ (self, other):
return self.a == other.b and self.b == other.b
</code></pre>