<p>您确实想通过实现<a href="http://docs.python.org/2/reference/datamodel.html#special-method-names" rel="nofollow">special Python hook methods</a>,将您的<code>is_after</code>方法合并到类本身来定义<code>Time()</code>类型的实例如何进行比较。在</p>
<p>一个<a href="http://docs.python.org/2/reference/datamodel.html#object.__eq__" rel="nofollow">^{<cd3>} method</a>将告诉Python两个对象是如何相等的,您可以使用<a href="http://docs.python.org/2/reference/datamodel.html#object.__lt__" rel="nofollow">^{<cd4>}</a>、<a href="http://docs.python.org/2/reference/datamodel.html#object.__gt__" rel="nofollow">^{<cd5>}</a>、<a href="http://docs.python.org/2/reference/datamodel.html#object.__le__" rel="nofollow">^{<cd6>}</a>和{a6}钩子来定义排序比较。在</p>
<p>使用<a href="http://docs.python.org/2/library/functools.html#functools.total_ordering" rel="nofollow">^{<cd8>} class decorator</a>最小化需要实现的方法数:</p>
<pre><code>from functools import total_ordering
@total_ordering
class Time(object):
def __init__(self, hour, minute, seconds):
self.hour, self.minute, self.seconds = hour, minute, seconds
def __eq__(self, other):
if not isinstance(other, type(self)): return NotImplemented
return all(getattr(self, a) == getattr(other, a) for a in ('hour', 'minute', 'second'))
def __lt__(self, other):
if not isinstance(other, type(self)): return NotImplemented
if self.hour < other.hour:
return True
if self.hour == other.hour:
if self.minute < other.minute:
return True
if self.minute == other.mitune:
return self.seconds < other.seconds
return False
</code></pre>
<p>现在您只需使用Python<code><</code>、<code><=</code>、<code>></code>、<code>>=</code>和{<cd14>}运算符直接比较<code>Time()</code>实例<em>:</p>
^{pr2}$